Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/web/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ RUN timeout 30s python3 scripts/codex-backend/check-capabilities.py "$THEOREMOS_
LABEL org.theoremos.native-agent-control=v1
LABEL org.theoremos.team-profile-preferences=v1
LABEL org.theoremos.team-expert-cards=v1
LABEL org.theoremos.worker-control=v1
ENTRYPOINT ["/opt/theorem-os/apps/web/worker-entrypoint.sh"]

FROM source AS web
Expand Down
20 changes: 15 additions & 5 deletions apps/web/agentActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,14 @@ export function isWebAgentActionBody(value: unknown): value is WebAgentActionBod

/** Coalesce only sanitized public text snapshots; lifecycle reports and tool actions remain immediate. */
export function createAgentActionStream(send: (action: WebAgentActionBody) => void) {
const reasoningIntervalMs = 4_000, reasoningPreviewBytes = 2_048;
const runningPreview = (action: WebAgentActionBody) => {
if (action.kind !== 'reasoning' || !action.text || Buffer.byteLength(action.text) <= reasoningPreviewBytes) return action;
const bytes = Buffer.from(action.text);
let start = bytes.length - reasoningPreviewBytes + Buffer.byteLength('…');
while ((bytes[start]! & 0xc0) === 0x80) start++;
return { ...action, text: '…' + bytes.toString('utf8', start), textClipped: true };
};
type Entry = { sentAt?: number; signature?: string; latest?: WebAgentActionBody; pending?: WebAgentActionBody;
timer?: ReturnType<typeof setTimeout>; completed?: boolean };
const entries = new Map<string, Entry>();
Expand Down Expand Up @@ -442,13 +450,15 @@ export function createAgentActionStream(send: (action: WebAgentActionBody) => vo
if (!action.textSource) { if (!incremental) deliver(action); return; }
if (!entry) { entry = {}; entries.set(itemId, entry); }
entry.latest = action;
if (!incremental) { emit(entry, action); return; }
if (entry.signature === signature(action)) {
const preview = runningPreview(action);
if (!incremental) { emit(entry, preview); return; }
if (entry.signature === signature(preview)) {
clearTimeout(entry.timer); entry.timer = undefined; entry.pending = undefined; return;
}
entry.pending = action;
const remaining = entry.sentAt === undefined ? 0 : Math.max(0, 1_000 - (Date.now() - entry.sentAt));
if (!remaining) { clearTimeout(entry.timer); entry.timer = undefined; emit(entry, action); }
entry.pending = preview;
const interval = action.kind === 'reasoning' ? reasoningIntervalMs : 1_000;
const remaining = entry.sentAt === undefined ? 0 : Math.max(0, interval - (Date.now() - entry.sentAt));
if (!remaining) { clearTimeout(entry.timer); entry.timer = undefined; emit(entry, preview); }
else if (!entry.timer) {
entry.timer = setTimeout(() => {
entry!.timer = undefined;
Expand Down
1 change: 1 addition & 0 deletions apps/web/collaboration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export type WebNativeTeamTask = { id: string; memberId: string; objective: strin
reassignment?: { ref: string; revision: number } };
export type WebNativeTeam = {
schema: 'theorem-os.web-native-team.v1'; runId: string;
transport?: 'native-agent-control' | 'host-tools';
maxAgents: number; memberCount: number; taskCount: number; taskOmissions: number;
tasks: WebNativeTeamTask[]; findings: WebTeamFinding[]; deliveries: WebTeamDelivery[]; adoptions: WebTeamAdoption[];
};
Expand Down
2 changes: 1 addition & 1 deletion apps/web/formalizationTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export type WebFormalizationRequest = { original: string; environment: WebEnviro
requestId?: string; providerId?: string; model?: string; researchEffort?: 'low' | 'high' | 'max'; maxRunSeconds?: number; maxTotalTokens?: number; research?: Partial<WebResearchBudget> };
export type WorkerFormalizationInput = Omit<WebFormalizationRequest, 'solve' | 'humanReview' | 'requestId' | 'providerId' | 'research' | 'researchEffort' | 'autoExplain' | 'explanationLanguage'> & { id: string; model: string; provider: WebWorkerProvider;
maxRunSeconds: number; maxTotalTokens: number; maxRounds: number; maxPlanningRounds: number; reviewers: number;
contextProtocol?: LeanStatementContextProtocol; reviewMode?: 'direct' };
contextProtocol?: LeanStatementContextProtocol; reviewMode?: 'direct'; outputDelivery?: 'native-schema' | 'file' };
export type WorkerFormalizationAuditMessage = { type: 'audit-progress'; tokens: number }
| { type: 'audit-result'; result: FormalizationAuditResult }
| { type: 'audit-error'; reason: string };
Expand Down
2 changes: 2 additions & 0 deletions apps/web/formalizationWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const formalizationWorkerInputObject = z.object({
reviewers: z.literal(webFormalizationLimits.reviewers),
contextProtocol: z.literal(LEAN_STATEMENT_CONTEXT_PROTOCOL).optional(),
reviewMode: z.literal('direct').optional(),
outputDelivery: z.enum(['native-schema', 'file']).optional(),
}).strict();
const providerConfiguration = (input: { provider: { id: string; baseUrl: string }; model: string }, context: z.RefinementCtx) => {
let url: URL;
Expand Down Expand Up @@ -81,6 +82,7 @@ export function webFormalizationPreparation(input: WorkerFormalizationInput, pro
...author, ...(input.reviewMode === 'direct' ? { reviewMode: 'direct' as const } :
{ workflow, fidelityPolicy: 'task-preserving-v2' as const }), buildManifestRef,
contextProtocol: input.contextProtocol ?? LEAN_STATEMENT_CONTEXT_PROTOCOL,
outputDelivery: input.outputDelivery ?? 'file',
maxRounds: input.maxRounds, maxRunSeconds: input.maxRunSeconds, maxTurnSeconds: 0, maxCompileSeconds: 0,
maxTotalTokens: input.maxTotalTokens };
}
Expand Down
2 changes: 2 additions & 0 deletions apps/web/i18n/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export const errors: Record<string, string> = {
'原生团队容量必须为 2 至 8 人(含 Lead)。': 'Choose a native team capacity of 2 to 8, including Lead.',
'原生团队需要 Codex 执行器。': 'Native teams require the Codex harness.',
'角色偏好仅适用于 Codex 原生团队。': 'Profile preferences require a native Codex team.',
'路线探索至少需要两名研究员。': 'Portfolio exploration requires at least two researchers.',
'路线探索时长必须在启用路线探索时设为 1 至 86400 秒的整数。': 'Set an exploration duration of 1 to 86400 whole seconds with portfolio exploration enabled.',
'当前运行镜像不支持个人专家资料。请移除专家资产或更新运行镜像。': 'This worker image does not support personal experts. Remove the selected expert assets or update the worker image.',
'每个个人专家在一次运行中只能选择一个发布版本。': 'Select only one release of each personal expert per run.',
'每次运行最多选择 32 个个人专家。': 'Select up to 32 personal experts per run.',
Expand Down
3 changes: 2 additions & 1 deletion apps/web/nativeTeamObservation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function projectWebNativeTeam(state: SolverRunState, runDirectory: string
committed: (archive: string, commit: string) => { files: Record<string, string>; digest: string },
): WebNativeTeam | undefined {
const team = state.agentTeam;
if (team?.transport !== 'native-agent-control') return;
if (!team || (team.transport !== 'native-agent-control' && state.researchDelegation?.mode !== 'team')) return;
const root = path.join(path.dirname(state.worktree), 'agent-team');
const contained = root !== runDirectory && isMathPathWithin(runDirectory, root);
const proofs = path.join(root, 'proofs'), archive = path.join(proofs, 'sources.git');
Expand Down Expand Up @@ -185,6 +185,7 @@ export function projectWebNativeTeam(state: SolverRunState, runDirectory: string
for (const reference of (team.researchArtifacts ?? []).slice(-16)) finding('research:' + reference.id);
for (const entry of mail.filter(entry => entry.originTaskId).slice(-24)) finding('message:' + entry.id);
return { schema: 'theorem-os.web-native-team.v1', runId: state.runId, maxAgents: inspection.maxAgents,
transport: team.transport ?? 'host-tools',
memberCount: overview.totals.workers, taskCount: overview.totals.tasks, taskOmissions: overview.totals.tasks - tasks.length,
tasks, findings: [...findings.values()], deliveries: published, adoptions };
}
54 changes: 54 additions & 0 deletions apps/web/observationSources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { mathDigest } from '../../src/math/mathRuntimeIo';
import type { WebObservation, WebTaskSource } from './collaboration';

type SourceReference = { sha256: string };
type ObservationWithSource<Text> = Omit<WebObservation, 'sources'> & {
sources: (Omit<WebTaskSource, 'source' | 'dependencySources'> & {
source: Text; dependencySources?: { file: string; source: Text }[];
})[];
};

export type CompactWebObservation = ObservationWithSource<SourceReference>;
export type WorkerObservationFrame = {
type: 'observation';
observation: CompactWebObservation;
sourceBlobs: Record<string, string>;
};

function mapSources<From, To>(observation: ObservationWithSource<From>, map: (source: From) => To): ObservationWithSource<To> {
return {
...observation,
sources: observation.sources.map(({ source, dependencySources, ...metadata }) => ({
...metadata, source: map(source),
...(dependencySources === undefined ? {} : {
dependencySources: dependencySources.map(dependency => ({ ...dependency, source: map(dependency.source) })),
}),
})),
};
}

export function compactObservation(observation: WebObservation, save: (digest: string, text: string) => void): CompactWebObservation {
const digests = new Map<string, string>();
return mapSources(observation, (source: string) => {
let sha256 = digests.get(source);
if (!sha256) {
sha256 = mathDigest(source);
digests.set(source, sha256);
save(sha256, source);
}
return { sha256 };
});
}

/** Legacy records inline their sources. References must all resolve before handing the observation to a consumer. */
export function hydrateObservation(observation: WebObservation | CompactWebObservation,
read: (digest: string) => string | undefined): WebObservation {
return mapSources(observation, (source: string | SourceReference) => {
if (typeof source === 'string') return source;
if (typeof source?.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(source.sha256))
throw new Error('web_observation_source_reference_invalid');
const text = read(source.sha256);
if (text === undefined) throw new Error('web_observation_source_blob_missing');
return text;
});
}
9 changes: 6 additions & 3 deletions apps/web/proofJournal.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'node:path';
import { writeMathTextDurable } from '../../src/math/mathRuntimeIo';
import type { WorkerMessage } from './shared';
import type { WorkerObservationFrame } from './observationSources';

export const webProofJournalDirectory = '/var/theoremos-proof';
export const webProofJournalFiles = ['transitions.json', 'observation.json', 'artifact.json', 'terminal.json'] as const;
Expand All @@ -15,8 +16,10 @@ export function webProofMessageSink(output: NodeJS.WritableStream, apiKey: strin
};
const transitions: Extract<WorkerMessage, { type: 'library_restart' }>[] = [];
let disconnected = false;
output.on('error', () => { disconnected = true; });
return (message: WorkerMessage) => {
const disconnect = () => { disconnected = true; };
output.on('error', disconnect);
output.on('close', disconnect);
return (message: WorkerMessage, frame?: WorkerObservationFrame) => {
if (journal) {
let file: typeof webProofJournalFiles[number] | undefined;
switch (message.type) {
Expand All @@ -35,6 +38,6 @@ export function webProofMessageSink(output: NodeJS.WritableStream, apiKey: strin
} catch { /* A failed backup write must not suppress the live result. */ }
}
}
if (!disconnected) output.write(redact(message) + '\n');
if (!disconnected) output.write(redact(frame ?? message) + '\n');
};
}
24 changes: 22 additions & 2 deletions apps/web/researchMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,27 @@ import type { WebProvider, WebRunInput } from './shared';

export const nativeTeamCapacitySchema = z.number().int().min(MIN_TEAM_AGENTS).max(MAX_TEAM_AGENTS);
export const nativeTeamPreferencesSchema = z.array(z.string().trim().min(1).max(100)).max(256);
export const webPortfolioSecondsSchema = z.number().int().min(1).max(86_400);

/** Team preset for Web callers. Capacity counts the Lead and its isolated members. */
export function webAgentTeamPreset(capacity = 3): Pick<WebRunInput, 'researchMode' | 'workers' | 'coordination' | 'nativeTeamCapacity'> {
return { researchMode: 'skill', workers: 1, coordination: 'independent', nativeTeamCapacity: nativeTeamCapacitySchema.parse(capacity) };
}

/** Presets can opt in at two or more workers. An explicit choice always wins. */
export function webPortfolioPreset(input: Pick<WebRunInput, 'workers' | 'nativeTeamCapacity' | 'portfolioExploration'>): boolean {
return input.portfolioExploration ?? (input.nativeTeamCapacity ?? input.workers) >= 2;
}

/** The optional research engine is frozen with each new run, never changed by an observation. */
export function webResearchModeError(input: Pick<WebRunInput, 'researchMode' | 'skillLoading' | 'workers' |
'coordination' | 'planApproval' | 'modulePlan' | 'researchSelection' | 'nativeTeamCapacity' | 'nativeTeamPreferredProfiles'>, provider?: Pick<WebProvider, 'harness'>): string | undefined {
'coordination' | 'planApproval' | 'modulePlan' | 'researchSelection' | 'nativeTeamCapacity' | 'nativeTeamPreferredProfiles' |
'portfolioExploration' | 'portfolioSeconds'>, provider?: Pick<WebProvider, 'harness'>): string | undefined {
if (input.portfolioExploration && (input.nativeTeamCapacity ?? input.workers) < 2)
return '路线探索至少需要两名研究员。';
if (input.portfolioSeconds !== undefined &&
(!input.portfolioExploration || !webPortfolioSecondsSchema.safeParse(input.portfolioSeconds).success))
return '路线探索时长必须在启用路线探索时设为 1 至 86400 秒的整数。';
if (input.nativeTeamPreferredProfiles?.length && input.nativeTeamCapacity === undefined) return '角色偏好仅适用于 Codex 原生团队。';
if (input.nativeTeamCapacity !== undefined) {
if (!nativeTeamCapacitySchema.safeParse(input.nativeTeamCapacity).success)
Expand All @@ -25,10 +42,13 @@ export function webResearchModeError(input: Pick<WebRunInput, 'researchMode' | '
export function webResearchArguments(input: WebRunInput, provider?: Pick<WebProvider, 'harness'>): string[] {
const error = webResearchModeError(input, provider);
if (error) throw new Error(error);
return input.researchMode === 'skill'
const research = input.researchMode === 'skill'
? ['--research-mode', 'skill', '--skill-loading', input.skillLoading ?? webDefaultSkillLoading(provider),
...(input.nativeTeamCapacity ? ['--skill-delegation', 'team', '--skill-max-agents', String(input.nativeTeamCapacity)] : []),
...(input.nativeTeamPreferredProfiles?.length ? ['--skill-preferred-profiles', input.nativeTeamPreferredProfiles.join(',')] : [])] : [];
if (input.portfolioExploration === undefined) return research;
return [...research, input.portfolioExploration ? '--portfolio-exploration' : '--skip-portfolio',
...(input.portfolioSeconds === undefined ? [] : ['--portfolio-seconds', String(input.portfolioSeconds)])];
}

/** A Skill changes research methods; only the execution arrangement controls collaboration. */
Expand Down
Loading
Loading