Skip to content
English

策略与缩减操作的真实调度目录 ​

策略的具体实现如下。

ts
contextPolicyCatalog = {
  validate: { validate() {}, run() {} },
  reduce: { validate: validateCorePolicy, run: reduceCore },
  audit: { validate: validateAppPolicy, run: auditApp },
} satisfies Record<ContextPolicy['mode'], PolicyHandler>

contextReductionCatalog = {
  trim: {
    validate(step) {
      if (step.kind !== 'trim') throw fail('Invalid trim step');
      validateRecentHistory(step);
    },
    run: trim,
  },
  compress: {
    validate(step, handlers) {
      if (step.kind !== 'compress') throw fail('Invalid compression step');
      breakWhile(!handlers.has(step.handlerId), fail('Unregistered context compressor'));
      if (step.preserve) validateRecentHistory(step.preserve);
    },
    run: compress,
  },
} satisfies Record<ContextReduction['kind'], Operation>

export function validateContextPolicy(
  policy: ContextPolicy,
  compressors: readonly ContextCompressor[],
  selectors: readonly ContextSelector[] = [],
): void {
  const handlers = new Set<string>();
  for (const handler of compressors) {
    breakWhile(
      !handler.id ||
        handlers.has(handler.id) ||
        typeof handler.compress !== 'function' ||
        !Number.isSafeInteger(contextHandlerCalls(handler)) ||
        contextHandlerCalls(handler) < 0,
      fail('Invalid context compressor'),
    );
    handlers.add(handler.id);
  }
  const mode = Object.hasOwn(contextPolicyCatalog, policy.mode)
    ? contextPolicyCatalog[policy.mode]
    : undefined;
  breakWhile(!mode, fail('Unknown context processing mode'));
  mode!.validate(policy, handlers);
  if (policy.mode === 'reduce')
    validateContextSelection(policy.selection ?? { mode: 'sequence' }, selectors);
}

export async function processContext(
  plan: ContextPlan,
  policy: ContextPolicy,
  ports: ProcessingPorts,
): Promise<{ context: BuiltContext; report: ContextProcessingReport }> {
  return nativeSubFlowAsync(ports, 'context', policy.mode, async () => {
    const state = beginContextProcessing(plan, policy, ports);
    await contextPolicyCatalog[policy.mode].run(state);
    return finishContextProcessing(state);
  });
}

接口参考、使用示例与开发指南。