@archboard/codex-realtime-voice 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { _ as JsonValueSchema, b as CODEX_APP_SERVER_CAPACITY, c as CODEX_REALTIME_MS, d as codexRestartDelayMs, f as BROWSER_PERMISSION_FILE_ACCESS, h as BROWSER_VOICE_CONTEXT_BRIEF_MAX_UTF8_BYTES, l as CODEX_SESSION_MS, m as BROWSER_VOICE_CONTEXT_BODY_MAX_UTF8_BYTES, o as CODEX_APPROVAL_MS, p as BROWSER_TIMELINE_LIMITS, s as CODEX_PROCESS_MS, t as createCodexBrowserModel, u as TAB_SESSION_GRACE_MS, y as boundedWireText } from "./model-YHUwnXnC.mjs";
1
+ import { _ as JsonValueSchema, b as CODEX_APP_SERVER_CAPACITY, c as CODEX_REALTIME_MS, d as codexRestartDelayMs, f as BROWSER_PERMISSION_FILE_ACCESS, h as BROWSER_VOICE_CONTEXT_BRIEF_MAX_UTF8_BYTES, l as CODEX_SESSION_MS, m as BROWSER_VOICE_CONTEXT_BODY_MAX_UTF8_BYTES, o as CODEX_APPROVAL_MS, p as BROWSER_TIMELINE_LIMITS, s as CODEX_PROCESS_MS, t as createCodexBrowserModel, u as TAB_SESSION_GRACE_MS, y as boundedWireText } from "./model-DnitkA24.mjs";
2
2
  import { c as CodexThreadStatusTypeSchema, n as CODEX_THREAD_STATUS_TYPES } from "./app-server-contract-D4E5bibD.mjs";
3
3
  import { a as createIdentityLedger, i as createIdentityAuthorities, o as logicalToolCallKey, r as parseRealtimeSessionId, s as IdentityValidationError, t as parseRealtimeCorrelationId } from "./realtime-contract-DwkCluo2.mjs";
4
- import { n as BROWSER_SNAPSHOT_DELTA_KEYS } from "./gateway-envelope-CODkg5rz.mjs";
5
- import { A as isSupportedResponseMethod, B as CodexServerResponseSchema, C as createCodexSession, D as decodeServerNotification, E as decodeResponseEnvelope, F as CODEX_PROTOCOL_BINARY_VERSION, G as cloneAndFreeze$3, H as SupportedLoginAccountParamsSchema, I as CODEX_PROTOCOL_VERSION, L as CODEX_SESSION_CONTROL, M as isClientRequestMethodWithoutParams, N as JSON_RPC_ERROR_CODES, O as decodeServerRequest, P as SERVER_REQUEST_SCHEMAS, R as CODEX_SESSION_THREAD_SOURCE, T as decodeJsonRpcError, U as ADDITIONAL_CONTEXT_POLICY, V as QueuedSubmissionSchema, W as createTextUserInput, _ as encodeManifest, a as createVoiceToolset, b as EMPTY_SPOKEN_APPROVAL_SNAPSHOT, c as answerUnownedTellCoordinator, d as WORKHORSE_TOOL_NAMES, f as canonicalTool, g as emptyManifest, h as decodeManifest, i as createWorkbenchThreadProfile, j as isSupportedServerRequestMethod, k as isSupportedClientNotificationMethod, l as createTellCoordinator, m as buildManifest, n as captureWorkbenchInstructions, o as toolRoleOf, p as deepFreeze$5, s as TELL_COORDINATOR_OWNER, t as captureThreadProfile, u as VOICE_TOOL_NAMES, v as manifestBytesHash, w as ProtocolDecodeError, x as createCodexRealtimeAdapter, y as operationRequiresThreadProvenance, z as CodexSessionMutationError } from "./instructions-CmBJHqpa.mjs";
4
+ import { n as BROWSER_SNAPSHOT_DELTA_KEYS } from "./gateway-envelope-DXTRMB3q.mjs";
5
+ import { A as isSupportedResponseMethod, B as CodexServerResponseSchema, C as createCodexSession, D as decodeServerNotification, E as decodeResponseEnvelope, F as CODEX_PROTOCOL_BINARY_VERSION, G as cloneAndFreeze$3, H as SupportedLoginAccountParamsSchema, I as CODEX_PROTOCOL_VERSION, L as CODEX_SESSION_CONTROL, M as isClientRequestMethodWithoutParams, N as JSON_RPC_ERROR_CODES, O as decodeServerRequest, P as SERVER_REQUEST_SCHEMAS, R as CODEX_SESSION_THREAD_SOURCE, T as decodeJsonRpcError, U as ADDITIONAL_CONTEXT_POLICY, V as QueuedSubmissionSchema, W as createTextUserInput, _ as encodeManifest, a as createVoiceToolset, b as EMPTY_SPOKEN_APPROVAL_SNAPSHOT, c as answerUnownedTellCoordinator, d as WORKHORSE_TOOL_NAMES, f as canonicalTool, g as emptyManifest, h as decodeManifest, i as createWorkbenchThreadProfile, j as isSupportedServerRequestMethod, k as isSupportedClientNotificationMethod, l as createTellCoordinator, m as buildManifest, n as captureWorkbenchInstructions, o as toolRoleOf, p as deepFreeze$5, s as TELL_COORDINATOR_OWNER, t as captureThreadProfile, u as VOICE_TOOL_NAMES, v as manifestBytesHash, w as ProtocolDecodeError, x as createCodexRealtimeAdapter, y as operationRequiresThreadProvenance, z as CodexSessionMutationError } from "./instructions-8ACs49yJ.mjs";
6
6
  import { createRequire } from "node:module";
7
7
  import { z } from "zod";
8
8
  import * as nodeFs from "node:fs";
@@ -578,7 +578,7 @@ function openBrowserSocket(browser, connection, surface, checkout) {
578
578
  * @param raw The complete frame bytes.
579
579
  * @returns The JSON request text.
580
580
  */
581
- function requestText(raw) {
581
+ function requestText$1(raw) {
582
582
  if (raw instanceof ArrayBuffer) return Buffer.from(raw).toString("utf8");
583
583
  if (Array.isArray(raw)) return Buffer.concat(raw).toString("utf8");
584
584
  return raw.toString("utf8");
@@ -621,7 +621,7 @@ function attachBrowserSockets(server, browser, options) {
621
621
  const session = openBrowserSocket(browser, connection, surface, checkout);
622
622
  if (session === null) return;
623
623
  connection.on("close", () => void session.end());
624
- connection.on("message", (raw, binary) => session.receive(binary ? null : requestText(raw)));
624
+ connection.on("message", (raw, binary) => session.receive(binary ? null : requestText$1(raw)));
625
625
  });
626
626
  };
627
627
  server.on("upgrade", upgrade);
@@ -1743,6 +1743,1543 @@ function createTabSessions(graceMs = TAB_SESSION_GRACE_MS) {
1743
1743
  onShownChange: (listener) => subscribe$1(shownListeners, listener)
1744
1744
  });
1745
1745
  }
1746
+ // src/runtime/voice/coordinator/tools-and-work/tool-contract/protocol/dynamic-tool-envelopes.ts
1747
+ const DYNAMIC_TOOL_REFUSAL_REASONS = Object.freeze([
1748
+ "invalid_call",
1749
+ "not_ready",
1750
+ "not_loaded",
1751
+ "not_controllable",
1752
+ "system_error",
1753
+ "stale_child",
1754
+ "prior_epoch",
1755
+ "unknown_provenance",
1756
+ "approval_declined",
1757
+ "cycle",
1758
+ "busy",
1759
+ "expired",
1760
+ "unsupported"
1761
+ ]);
1762
+ const DynamicToolRefusalReasonSchema = z.enum(DYNAMIC_TOOL_REFUSAL_REASONS);
1763
+ const OpaqueIdSchema = z.string().min(1).max(128);
1764
+ const BoundedDiagnosticSchema = z.string().min(1).max(4096);
1765
+ const JsonObjectSchema = z.record(z.string(), z.json());
1766
+ const DynamicToolOkEnvelopeSchema = z.object({
1767
+ tag: z.literal("ok"),
1768
+ operationId: OpaqueIdSchema,
1769
+ value: JsonObjectSchema
1770
+ }).strict();
1771
+ const DynamicToolRefusedEnvelopeSchema = z.object({
1772
+ tag: z.literal("refused"),
1773
+ reason: DynamicToolRefusalReasonSchema,
1774
+ message: BoundedDiagnosticSchema
1775
+ }).strict();
1776
+ const DynamicToolApprovalRequiredEnvelopeSchema = z.object({
1777
+ tag: z.literal("approval_required"),
1778
+ operationId: OpaqueIdSchema,
1779
+ summary: BoundedDiagnosticSchema
1780
+ }).strict();
1781
+ const DYNAMIC_TOOL_OUTCOME_UNKNOWN_MESSAGE = "The request may have taken effect. Inspect authoritative state before another mutation.";
1782
+ const DynamicToolOutcomeUnknownEnvelopeSchema = z.object({
1783
+ tag: z.literal("outcome_unknown"),
1784
+ operationId: OpaqueIdSchema,
1785
+ message: z.literal(DYNAMIC_TOOL_OUTCOME_UNKNOWN_MESSAGE)
1786
+ }).strict();
1787
+ const DynamicToolEnvelopeSchema = z.discriminatedUnion("tag", [
1788
+ DynamicToolOkEnvelopeSchema,
1789
+ DynamicToolRefusedEnvelopeSchema,
1790
+ DynamicToolApprovalRequiredEnvelopeSchema,
1791
+ DynamicToolOutcomeUnknownEnvelopeSchema
1792
+ ]);
1793
+ const DynamicToolEnvelopeTextSchema = z.string().min(1).max(16384).superRefine((text, context) => {
1794
+ let value;
1795
+ try {
1796
+ value = JSON.parse(text);
1797
+ } catch {
1798
+ context.addIssue({
1799
+ code: "custom",
1800
+ message: "tool response text must be JSON"
1801
+ });
1802
+ return;
1803
+ }
1804
+ const parsed = DynamicToolEnvelopeSchema.safeParse(value);
1805
+ if (!parsed.success || JSON.stringify(parsed.data) !== text) context.addIssue({
1806
+ code: "custom",
1807
+ message: "tool response text must be canonical JSON"
1808
+ });
1809
+ });
1810
+ const DynamicToolContentItemsSchema = z.tuple([z.object({
1811
+ type: z.literal("inputText"),
1812
+ text: DynamicToolEnvelopeTextSchema
1813
+ }).strict()]);
1814
+ /** Responses for calls that passed the coordinator's identity/manifest checks. */
1815
+ const ValidDynamicToolResponseSchema = z.object({
1816
+ contentItems: DynamicToolContentItemsSchema,
1817
+ success: z.literal(true)
1818
+ }).strict();
1819
+ /**
1820
+ * Reads the envelope tag out of response text without trusting it to be an envelope.
1821
+ * @param text - The tool response text.
1822
+ * @returns The tag when the text is a valid envelope, otherwise undefined.
1823
+ */
1824
+ function envelopeTag(text) {
1825
+ let value;
1826
+ try {
1827
+ value = JSON.parse(text);
1828
+ } catch {
1829
+ return;
1830
+ }
1831
+ const parsed = DynamicToolEnvelopeSchema.safeParse(value);
1832
+ return parsed.success ? parsed.data.tag : void 0;
1833
+ }
1834
+ /** Responses for calls rejected before a tool call could be established. */
1835
+ const UnknownDynamicToolResponseSchema = z.object({
1836
+ contentItems: DynamicToolContentItemsSchema,
1837
+ success: z.literal(false)
1838
+ }).strict().superRefine((response, context) => {
1839
+ if (envelopeTag(response.contentItems[0].text) !== "refused") context.addIssue({
1840
+ code: "custom",
1841
+ path: ["contentItems"],
1842
+ message: "unknown calls must return a refused envelope"
1843
+ });
1844
+ });
1845
+ // src/runtime/voice/coordinator/tools-and-work/tool-contract/protocol/tool-inputs.ts
1846
+ /**
1847
+ * The checkout whose workhorse a tool works with: the directory the host names it by.
1848
+ */
1849
+ const CheckoutSchema = z.string().min(1).max(4096);
1850
+ const InspectWorkhorseInputSchema = z.object({ checkout: CheckoutSchema }).strict();
1851
+ const DelegateToWorkhorseInputSchema = z.object({
1852
+ checkout: CheckoutSchema,
1853
+ input: z.string().min(1).max(4096),
1854
+ transcriptDelta: z.string().min(0).max(4096)
1855
+ }).strict();
1856
+ const QueueOperationSchema = z.enum([
1857
+ "list",
1858
+ "add",
1859
+ "update",
1860
+ "delete",
1861
+ "reorder",
1862
+ "start"
1863
+ ]);
1864
+ const QueueSubmissionIdSchema = z.string().min(1).max(128);
1865
+ const QueuePromptSchema = z.string().min(1).max(16384);
1866
+ const QueueOrderSchema = z.array(QueueSubmissionIdSchema).min(1).max(100).refine((values) => new Set(values).size === values.length, "submission ids must be unique");
1867
+ const QueueListInputSchema = z.object({
1868
+ checkout: CheckoutSchema,
1869
+ operation: z.literal("list")
1870
+ }).strict();
1871
+ const QueueAddInputSchema = z.object({
1872
+ checkout: CheckoutSchema,
1873
+ operation: z.literal("add"),
1874
+ prompt: QueuePromptSchema
1875
+ }).strict();
1876
+ const QueueUpdateInputSchema = z.object({
1877
+ checkout: CheckoutSchema,
1878
+ operation: z.literal("update"),
1879
+ submissionId: QueueSubmissionIdSchema,
1880
+ prompt: QueuePromptSchema
1881
+ }).strict();
1882
+ const QueueDeleteInputSchema = z.object({
1883
+ checkout: CheckoutSchema,
1884
+ operation: z.literal("delete"),
1885
+ submissionId: QueueSubmissionIdSchema
1886
+ }).strict();
1887
+ const QueueReorderInputSchema = z.object({
1888
+ checkout: CheckoutSchema,
1889
+ operation: z.literal("reorder"),
1890
+ orderedSubmissionIds: QueueOrderSchema
1891
+ }).strict();
1892
+ const QueueStartInputSchema = z.object({
1893
+ checkout: CheckoutSchema,
1894
+ operation: z.literal("start"),
1895
+ submissionId: QueueSubmissionIdSchema
1896
+ }).strict();
1897
+ const ManageWorkhorseQueueInputSchema = z.discriminatedUnion("operation", [
1898
+ QueueListInputSchema,
1899
+ QueueAddInputSchema,
1900
+ QueueUpdateInputSchema,
1901
+ QueueDeleteInputSchema,
1902
+ QueueReorderInputSchema,
1903
+ QueueStartInputSchema
1904
+ ]);
1905
+ const SteerWorkhorseInputSchema = z.object({
1906
+ checkout: CheckoutSchema,
1907
+ input: z.string().min(1).max(4096)
1908
+ }).strict();
1909
+ /** A stop names no workhorse: it stops every running workhorse of the calling tab session. */
1910
+ const StopWorkhorsesInputSchema = z.object({}).strict();
1911
+ const ResolveSpokenApprovalInputSchema = z.object({ verdict: z.enum(["accept", "decline"]) }).strict();
1912
+ const WORKHORSE_TOOL_INPUT_SCHEMAS = Object.freeze({
1913
+ inspect_workhorse: InspectWorkhorseInputSchema,
1914
+ delegate_to_workhorse: DelegateToWorkhorseInputSchema,
1915
+ manage_workhorse_queue: ManageWorkhorseQueueInputSchema,
1916
+ steer_workhorse: SteerWorkhorseInputSchema,
1917
+ stop_workhorses: StopWorkhorsesInputSchema
1918
+ });
1919
+ const VOICE_TOOL_INPUT_SCHEMAS = Object.freeze({ resolve_spoken_approval: ResolveSpokenApprovalInputSchema });
1920
+ /**
1921
+ * Validates the arguments the coordinator passed to one workhorse tool.
1922
+ * @param toolName - The workhorse tool being called.
1923
+ * @param input - The raw tool arguments.
1924
+ * @returns The validated arguments.
1925
+ */
1926
+ function parseWorkhorseToolInput(toolName, input) {
1927
+ return WORKHORSE_TOOL_INPUT_SCHEMAS[toolName].parse(input);
1928
+ }
1929
+ /**
1930
+ * Validates the arguments the coordinator passed to one voice tool.
1931
+ * @param toolName - The voice tool being called.
1932
+ * @param input - The raw tool arguments.
1933
+ * @returns The validated arguments.
1934
+ */
1935
+ function parseVoiceToolInput(toolName, input) {
1936
+ return VOICE_TOOL_INPUT_SCHEMAS[toolName].parse(input);
1937
+ }
1938
+ /**
1939
+ * Narrows a tool name to the workhorse namespace.
1940
+ * @param toolName - Any coordinator tool name.
1941
+ * @returns Whether the workhorse namespace declares the tool.
1942
+ */
1943
+ function isWorkhorseToolName(toolName) {
1944
+ return WORKHORSE_TOOL_NAMES.some((candidate) => candidate === toolName);
1945
+ }
1946
+ /**
1947
+ * Narrows a tool name to the voice namespace.
1948
+ * @param toolName - Any coordinator tool name.
1949
+ * @returns Whether the voice namespace declares the tool.
1950
+ */
1951
+ function isVoiceToolName(toolName) {
1952
+ return VOICE_TOOL_NAMES.some((candidate) => candidate === toolName);
1953
+ }
1954
+ /**
1955
+ * Validates tool arguments against the schema of the namespace the call arrived in, refusing
1956
+ * a tool name the namespace does not declare even when another namespace does.
1957
+ * @param role - The role of the namespace the call was made through.
1958
+ * @param toolName - The tool being called.
1959
+ * @param input - The raw tool arguments.
1960
+ * @returns The validated arguments.
1961
+ */
1962
+ function parseCoordinatorToolInput(role, toolName, input) {
1963
+ if (role === "workhorse") {
1964
+ if (!isWorkhorseToolName(toolName)) throw new TypeError(`The ${role} namespace does not declare ${toolName}.`);
1965
+ return parseWorkhorseToolInput(toolName, input);
1966
+ }
1967
+ if (!isVoiceToolName(toolName)) throw new TypeError(`The ${role} namespace does not declare ${toolName}.`);
1968
+ return parseVoiceToolInput(toolName, input);
1969
+ }
1970
+ // src/runtime/voice/coordinator/tools-and-work/tool-contract/protocol/tool-results.ts
1971
+ const DeliverySchema = z.enum([
1972
+ "delivered",
1973
+ "not_delivered",
1974
+ "outcome_unknown"
1975
+ ]);
1976
+ const NullableOpaqueIdSchema = OpaqueIdSchema.nullable();
1977
+ const QueuedSubmissionIdsSchema = z.array(QueueSubmissionIdSchema).max(100);
1978
+ const STOP_OUTCOMES = [
1979
+ "stopped",
1980
+ "idle",
1981
+ "partial",
1982
+ "unconfirmed"
1983
+ ];
1984
+ const REMAINING_STATES = [
1985
+ "running",
1986
+ "queued",
1987
+ "unread"
1988
+ ];
1989
+ const INSPECT_READS = [
1990
+ "turns",
1991
+ "subAgents",
1992
+ "queue"
1993
+ ];
1994
+ /** What a partial or unconfirmed stop leaves to do: look again, or stop again. */
1995
+ const STOP_RECOVERY = ["inspect_workhorse", "stop_workhorses"];
1996
+ const INSPECT_TEXT_LIMIT = 400;
1997
+ const RemainingWorkSchema = z.array(z.object({
1998
+ threadId: OpaqueIdSchema,
1999
+ state: z.enum(REMAINING_STATES)
2000
+ }).strict()).max(100);
2001
+ const InspectWorkhorseResultSchema = z.object({
2002
+ threadId: OpaqueIdSchema,
2003
+ status: CodexThreadStatusTypeSchema,
2004
+ activeTurnId: NullableOpaqueIdSchema,
2005
+ request: z.string().max(INSPECT_TEXT_LIMIT).nullable(),
2006
+ recentProgress: z.array(z.string().max(INSPECT_TEXT_LIMIT)).max(3),
2007
+ subAgents: z.array(z.object({
2008
+ threadId: OpaqueIdSchema,
2009
+ status: CodexThreadStatusTypeSchema
2010
+ }).strict()).max(50),
2011
+ queuedSubmissionIds: QueuedSubmissionIdsSchema,
2012
+ unavailable: z.array(z.enum(INSPECT_READS)).max(INSPECT_READS.length),
2013
+ lastStop: z.object({
2014
+ outcome: z.enum(["stopping", ...STOP_OUTCOMES]),
2015
+ remaining: RemainingWorkSchema
2016
+ }).strict().nullable()
2017
+ }).strict();
2018
+ const DelegateToWorkhorseResultSchema = z.object({
2019
+ mode: z.enum(["started", "queued"]),
2020
+ clientUserMessageId: OpaqueIdSchema,
2021
+ queuedSubmissionId: NullableOpaqueIdSchema,
2022
+ turnId: NullableOpaqueIdSchema
2023
+ }).strict();
2024
+ const ManageWorkhorseQueueResultSchema = z.object({
2025
+ operation: QueueOperationSchema,
2026
+ queuedSubmissionIds: QueuedSubmissionIdsSchema
2027
+ }).strict();
2028
+ const SteerWorkhorseResultSchema = z.object({
2029
+ turnId: OpaqueIdSchema,
2030
+ delivery: DeliverySchema
2031
+ }).strict();
2032
+ const StopWorkhorsesResultSchema = z.object({ stopped: z.array(z.object({
2033
+ checkout: z.string().min(1).max(4096),
2034
+ outcome: z.enum(STOP_OUTCOMES),
2035
+ remaining: RemainingWorkSchema,
2036
+ recovery: z.array(z.enum(STOP_RECOVERY)).max(STOP_RECOVERY.length)
2037
+ }).strict()).max(100) }).strict();
2038
+ const ResolveSpokenApprovalResultSchema = z.object({
2039
+ verdict: z.enum(["accept", "decline"]),
2040
+ settlement: DeliverySchema
2041
+ }).strict();
2042
+ const COORDINATOR_TOOL_RESULT_SCHEMAS = Object.freeze({
2043
+ inspect_workhorse: InspectWorkhorseResultSchema,
2044
+ delegate_to_workhorse: DelegateToWorkhorseResultSchema,
2045
+ manage_workhorse_queue: ManageWorkhorseQueueResultSchema,
2046
+ steer_workhorse: SteerWorkhorseResultSchema,
2047
+ stop_workhorses: StopWorkhorsesResultSchema,
2048
+ resolve_spoken_approval: ResolveSpokenApprovalResultSchema
2049
+ });
2050
+ /**
2051
+ * Validates the value a server produced for one coordinator tool before it is returned to the
2052
+ * model, so a malformed server result is refused rather than echoed as a success.
2053
+ * @param toolName - The tool whose result is being checked.
2054
+ * @param value - The raw server result.
2055
+ * @returns The validated result value.
2056
+ */
2057
+ function parseCoordinatorToolResult(toolName, value) {
2058
+ return COORDINATOR_TOOL_RESULT_SCHEMAS[toolName].parse(value);
2059
+ }
2060
+ const JsonStringSchema = Object.freeze({ type: "string" });
2061
+ const JsonNullableStringSchema = deepFreeze$5({ anyOf: [JsonStringSchema, Object.freeze({ type: "null" })] });
2062
+ /**
2063
+ * Builds the closed JSON Schema object that mirrors one zod result schema for the manifest.
2064
+ * @param properties - The JSON Schema of each result field.
2065
+ * @param required - The fields every result must carry.
2066
+ * @returns A frozen JSON Schema object that rejects unknown fields.
2067
+ */
2068
+ function strictResultObject(properties, required) {
2069
+ return deepFreeze$5({
2070
+ type: "object",
2071
+ properties,
2072
+ required: [...required],
2073
+ additionalProperties: false
2074
+ });
2075
+ }
2076
+ const ResultOperationSchema = deepFreeze$5({
2077
+ type: "string",
2078
+ enum: [...QueueOperationSchema.options]
2079
+ });
2080
+ const ResultStatusSchema = deepFreeze$5({
2081
+ type: "string",
2082
+ enum: [...CODEX_THREAD_STATUS_TYPES]
2083
+ });
2084
+ const ResultDeliverySchema = deepFreeze$5({
2085
+ type: "string",
2086
+ enum: [
2087
+ "delivered",
2088
+ "not_delivered",
2089
+ "outcome_unknown"
2090
+ ]
2091
+ });
2092
+ const ResultQueuedSubmissionIdsSchema = deepFreeze$5({
2093
+ type: "array",
2094
+ items: JsonStringSchema,
2095
+ maxItems: 100
2096
+ });
2097
+ const ResultRemainingWorkSchema = deepFreeze$5({
2098
+ type: "array",
2099
+ maxItems: 100,
2100
+ items: strictResultObject({
2101
+ threadId: JsonStringSchema,
2102
+ state: deepFreeze$5({
2103
+ type: "string",
2104
+ enum: [...REMAINING_STATES]
2105
+ })
2106
+ }, ["threadId", "state"])
2107
+ });
2108
+ const TOOL_SUCCESS_RESULT_SCHEMAS = deepFreeze$5({
2109
+ inspect_workhorse: strictResultObject({
2110
+ threadId: JsonStringSchema,
2111
+ status: ResultStatusSchema,
2112
+ activeTurnId: JsonNullableStringSchema,
2113
+ request: JsonNullableStringSchema,
2114
+ recentProgress: deepFreeze$5({
2115
+ type: "array",
2116
+ items: JsonStringSchema,
2117
+ maxItems: 3
2118
+ }),
2119
+ subAgents: deepFreeze$5({
2120
+ type: "array",
2121
+ maxItems: 50,
2122
+ items: strictResultObject({
2123
+ threadId: JsonStringSchema,
2124
+ status: ResultStatusSchema
2125
+ }, ["threadId", "status"])
2126
+ }),
2127
+ queuedSubmissionIds: ResultQueuedSubmissionIdsSchema,
2128
+ unavailable: deepFreeze$5({
2129
+ type: "array",
2130
+ items: deepFreeze$5({
2131
+ type: "string",
2132
+ enum: [...INSPECT_READS]
2133
+ })
2134
+ }),
2135
+ lastStop: deepFreeze$5({ anyOf: [strictResultObject({
2136
+ outcome: deepFreeze$5({
2137
+ type: "string",
2138
+ enum: ["stopping", ...STOP_OUTCOMES]
2139
+ }),
2140
+ remaining: ResultRemainingWorkSchema
2141
+ }, ["outcome", "remaining"]), Object.freeze({ type: "null" })] })
2142
+ }, [
2143
+ "threadId",
2144
+ "status",
2145
+ "activeTurnId",
2146
+ "request",
2147
+ "recentProgress",
2148
+ "subAgents",
2149
+ "queuedSubmissionIds",
2150
+ "unavailable",
2151
+ "lastStop"
2152
+ ]),
2153
+ delegate_to_workhorse: strictResultObject({
2154
+ mode: deepFreeze$5({
2155
+ type: "string",
2156
+ enum: ["started", "queued"]
2157
+ }),
2158
+ clientUserMessageId: JsonStringSchema,
2159
+ queuedSubmissionId: JsonNullableStringSchema,
2160
+ turnId: JsonNullableStringSchema
2161
+ }, [
2162
+ "mode",
2163
+ "clientUserMessageId",
2164
+ "queuedSubmissionId",
2165
+ "turnId"
2166
+ ]),
2167
+ manage_workhorse_queue: strictResultObject({
2168
+ operation: ResultOperationSchema,
2169
+ queuedSubmissionIds: ResultQueuedSubmissionIdsSchema
2170
+ }, ["operation", "queuedSubmissionIds"]),
2171
+ steer_workhorse: strictResultObject({
2172
+ turnId: JsonStringSchema,
2173
+ delivery: ResultDeliverySchema
2174
+ }, ["turnId", "delivery"]),
2175
+ stop_workhorses: strictResultObject({ stopped: deepFreeze$5({
2176
+ type: "array",
2177
+ maxItems: 100,
2178
+ items: strictResultObject({
2179
+ checkout: deepFreeze$5({
2180
+ type: "string",
2181
+ minLength: 1,
2182
+ maxLength: 4096
2183
+ }),
2184
+ outcome: deepFreeze$5({
2185
+ type: "string",
2186
+ enum: [...STOP_OUTCOMES]
2187
+ }),
2188
+ remaining: ResultRemainingWorkSchema,
2189
+ recovery: deepFreeze$5({
2190
+ type: "array",
2191
+ items: deepFreeze$5({
2192
+ type: "string",
2193
+ enum: [...STOP_RECOVERY]
2194
+ })
2195
+ })
2196
+ }, [
2197
+ "checkout",
2198
+ "outcome",
2199
+ "remaining",
2200
+ "recovery"
2201
+ ])
2202
+ }) }, ["stopped"]),
2203
+ resolve_spoken_approval: strictResultObject({
2204
+ verdict: deepFreeze$5({
2205
+ type: "string",
2206
+ enum: ["accept", "decline"]
2207
+ }),
2208
+ settlement: ResultDeliverySchema
2209
+ }, ["verdict", "settlement"])
2210
+ });
2211
+ Object.freeze([
2212
+ "list",
2213
+ "add",
2214
+ "update",
2215
+ "delete",
2216
+ "reorder",
2217
+ "start"
2218
+ ]);
2219
+ var CodexWorkhorseQueueError = class extends Error {
2220
+ name = "CodexWorkhorseQueueError";
2221
+ code;
2222
+ operation;
2223
+ outcome;
2224
+ queue;
2225
+ cause;
2226
+ /**
2227
+ * Build the error, defaulting every optional fact to null so a caller can always ask what the
2228
+ * failure proved about delivery and about the queue without checking whether the field exists.
2229
+ * @param code - Why the queue refused.
2230
+ * @param message - The diagnostic for the caller.
2231
+ * @param options - The operation, settled outcome, queue snapshot and underlying cause, as far
2232
+ * as they are known at the point of failure.
2233
+ */
2234
+ constructor(code, message, options = {}) {
2235
+ super(message);
2236
+ this.code = code;
2237
+ this.operation = options.operation ?? null;
2238
+ this.outcome = options.outcome ?? null;
2239
+ this.queue = options.queue ?? null;
2240
+ this.cause = options.cause;
2241
+ }
2242
+ };
2243
+ // src/runtime/workhorses/workhorse-operations/protocol/contract.ts
2244
+ Object.freeze([
2245
+ "inspect_workhorse",
2246
+ "delegate_to_workhorse",
2247
+ "manage_workhorse_queue",
2248
+ "steer_workhorse"
2249
+ ]);
2250
+ var CodexWorkhorseOperationsError = class extends Error {
2251
+ name = "CodexWorkhorseOperationsError";
2252
+ code;
2253
+ operation;
2254
+ outcome;
2255
+ operationId;
2256
+ cause;
2257
+ /**
2258
+ * Build the error, defaulting every optional fact to null so a caller can always ask what the
2259
+ * failure proved about delivery without checking whether the field exists.
2260
+ * @param code - Why the operation could not proceed.
2261
+ * @param message - The diagnostic for the caller.
2262
+ * @param options - The operation, settled outcome, operation identity and underlying cause,
2263
+ * as far as they are known at the point of failure.
2264
+ */
2265
+ constructor(code, message, options = {}) {
2266
+ super(message);
2267
+ this.code = code;
2268
+ this.operation = options.operation ?? null;
2269
+ this.outcome = options.outcome ?? null;
2270
+ this.operationId = options.operationId ?? null;
2271
+ this.cause = options.cause;
2272
+ }
2273
+ };
2274
+ // src/runtime/workhorses/workhorse-operations/rules/operation-errors.ts
2275
+ /**
2276
+ * Thread-link refusal reasons that map to a specific operation error code; every other reason
2277
+ * means the link is simply not ready.
2278
+ */
2279
+ const LINK_REASON_CODES = Object.freeze({
2280
+ stale_child: "stale_child",
2281
+ prior_epoch: "prior_epoch",
2282
+ thread_status_not_loaded: "not_loaded",
2283
+ thread_status_system_error: "system_error",
2284
+ direct_input_false: "not_controllable",
2285
+ direct_input_unknown: "not_controllable",
2286
+ thread_start_outcome_unknown: "unknown_provenance",
2287
+ unknown_provenance: "unknown_provenance",
2288
+ thread_list_missing: "unknown_provenance",
2289
+ thread_list_ambiguous: "unknown_provenance",
2290
+ thread_loaded_list_ambiguous: "unknown_provenance",
2291
+ thread_source_custom: "unknown_provenance",
2292
+ thread_source_subagent: "unknown_provenance",
2293
+ thread_source_unknown: "unknown_provenance",
2294
+ thread_loaded_list_missing: "unknown_provenance"
2295
+ });
2296
+ /** Queue error codes that leave the remote effect's outcome undecidable once it has started. */
2297
+ const UNDECIDABLE_QUEUE_CODES = /* @__PURE__ */ new Set(["reconciliation_failed", "stale_link"]);
2298
+ /**
2299
+ * Build an operations error; the one constructor call site keeps the option shape in one place.
2300
+ * @param code - The error code the caller can act on.
2301
+ * @param message - The human-readable reason.
2302
+ * @param options - Operation, outcome, identity and cause metadata.
2303
+ * @returns The error, not yet thrown.
2304
+ */
2305
+ function operationError(code, message, options = {}) {
2306
+ return new CodexWorkhorseOperationsError(code, message, options);
2307
+ }
2308
+ /**
2309
+ * Read a message from any thrown value for event detail and error chaining.
2310
+ * @param error - The thrown value.
2311
+ * @returns Its message, or a placeholder for non-Error throws.
2312
+ */
2313
+ function messageOf(error) {
2314
+ return error instanceof Error ? error.message : "unknown error";
2315
+ }
2316
+ /**
2317
+ * Translate a thread-link refusal reason into the operation error code callers act on.
2318
+ * @param reason - The classifier's reason string.
2319
+ * @returns The matching operation error code, `not_ready` for unmapped reasons.
2320
+ */
2321
+ function mapLinkReason(reason) {
2322
+ return LINK_REASON_CODES[reason] ?? "not_ready";
2323
+ }
2324
+ /**
2325
+ * Decide what a failed session mutation proved about delivery.
2326
+ * @param error - The thrown value from the session port.
2327
+ * @returns The outcome the session asserted, or unknown when it asserted nothing.
2328
+ */
2329
+ function sessionMutationOutcome(error) {
2330
+ return error instanceof CodexSessionMutationError ? error.outcome : "outcome_unknown";
2331
+ }
2332
+ /**
2333
+ * Decide what a failed queue mutation proved about delivery. Refusals raised by this module
2334
+ * or undecidable queue failures are unknown once the remote effect may have started, and
2335
+ * not delivered before that point.
2336
+ * @param error - The thrown value from the queue port or a pre-effect check.
2337
+ * @param effectStarted - Whether the remote effect had been issued when the error surfaced.
2338
+ * @returns The outcome to settle durably.
2339
+ */
2340
+ function queueMutationOutcome(error, effectStarted = true) {
2341
+ if (isUndecidableFailure(error)) return effectStarted ? "outcome_unknown" : "not_delivered";
2342
+ return assertedQueueOutcome(error) ?? "not_delivered";
2343
+ }
2344
+ /**
2345
+ * Recognise a failure that says nothing about the remote effect: a refusal raised by this module
2346
+ * after the effect may have started, or a queue error whose code is itself undecidable.
2347
+ * @param error - The thrown value.
2348
+ * @returns Whether the remote outcome is undecidable from this error alone.
2349
+ */
2350
+ function isUndecidableFailure(error) {
2351
+ return error instanceof CodexWorkhorseOperationsError || isUndecidableQueueError(error);
2352
+ }
2353
+ /**
2354
+ * The delivery outcome a queue error asserts, when it asserts one.
2355
+ * @param error - The thrown value.
2356
+ * @returns The asserted outcome, or null when the error asserts none.
2357
+ */
2358
+ function assertedQueueOutcome(error) {
2359
+ return error instanceof CodexWorkhorseQueueError ? error.outcome : null;
2360
+ }
2361
+ /**
2362
+ * Recognise a queue error whose code means the remote outcome cannot be decided.
2363
+ * @param error - The thrown value.
2364
+ * @returns Whether the error is a queue error with an undecidable code.
2365
+ */
2366
+ function isUndecidableQueueError(error) {
2367
+ return error instanceof CodexWorkhorseQueueError && UNDECIDABLE_QUEUE_CODES.has(error.code);
2368
+ }
2369
+ // src/runtime/workhorses/workhorse-operations/rules/internal.ts
2370
+ const INPUT_LIMIT_BYTES = 4096;
2371
+ const ATTENTION_FLAGS = /* @__PURE__ */ new Set(["waitingOnApproval", "waitingOnUserInput"]);
2372
+ /** The fields that make two coordinator calls the same logical call. */
2373
+ const CALL_IDENTITY_KEYS = [
2374
+ "child",
2375
+ "epoch",
2376
+ "threadId",
2377
+ "turnId",
2378
+ "callId",
2379
+ "namespace",
2380
+ "tool",
2381
+ "manifestHash"
2382
+ ];
2383
+ /**
2384
+ * Freeze a value with its type preserved, so snapshots handed to callers stay immutable.
2385
+ * @param value - The value to freeze.
2386
+ * @returns The same value, frozen.
2387
+ */
2388
+ function freeze$3(value) {
2389
+ return Object.freeze(value);
2390
+ }
2391
+ /**
2392
+ * Trim a detail string to the input byte budget so an event never carries unbounded text.
2393
+ * @param value - The detail text to bound.
2394
+ * @returns The text unchanged when it fits, otherwise a byte-bounded prefix with an ellipsis.
2395
+ */
2396
+ function boundedDetail(value) {
2397
+ if (Buffer.byteLength(value, "utf8") <= INPUT_LIMIT_BYTES) return value;
2398
+ const suffix = "...";
2399
+ const budget = INPUT_LIMIT_BYTES - Buffer.byteLength(suffix, "utf8");
2400
+ let bytes = 0;
2401
+ let prefix = "";
2402
+ for (const character of value) {
2403
+ const characterBytes = Buffer.byteLength(character, "utf8");
2404
+ if (bytes + characterBytes > budget) break;
2405
+ prefix += character;
2406
+ bytes += characterBytes;
2407
+ }
2408
+ return `${prefix}${suffix}`;
2409
+ }
2410
+ /**
2411
+ * Compare two coordinator calls field by field; a call is trusted only when every identity
2412
+ * component matches the one the server is currently executing.
2413
+ * @param left - One coordinator call.
2414
+ * @param right - The other coordinator call.
2415
+ * @returns Whether both calls name the same logical tool call.
2416
+ */
2417
+ function sameCall$1(left, right) {
2418
+ return CALL_IDENTITY_KEYS.every((key) => left[key] === right[key]);
2419
+ }
2420
+ /**
2421
+ * Compare two operation targets by child, epoch, thread and operation identity.
2422
+ * @param left - One target.
2423
+ * @param right - The other target.
2424
+ * @returns Whether both targets name the same linked thread under the same ownership.
2425
+ */
2426
+ function sameTarget$1(left, right) {
2427
+ return left.childId === right.childId && left.epoch === right.epoch && left.threadId === right.threadId && left.operationId === right.operationId;
2428
+ }
2429
+ /**
2430
+ * Compare two bindings, including both linked targets.
2431
+ * @param left - One binding.
2432
+ * @param right - The other binding.
2433
+ * @returns Whether both bindings link the same coordinator and workhorse under the same epoch.
2434
+ */
2435
+ function sameBinding$4(left, right) {
2436
+ return left.childId === right.childId && left.epoch === right.epoch && sameTarget$1(left.coordinator, right.coordinator) && sameTarget$1(left.workhorse, right.workhorse);
2437
+ }
2438
+ /**
2439
+ * Compare two bindings by their epoch and workhorse alone. An accepted operation belongs to its
2440
+ * workhorse turn, and it follows that turn to the end even after a voice start replaces the
2441
+ * coordinator that asked for it; what it reports then reaches no coordinator.
2442
+ * @param left - One binding.
2443
+ * @param right - The other binding.
2444
+ * @returns Whether both bindings name the same workhorse under the same epoch.
2445
+ */
2446
+ function sameWorkhorse(left, right) {
2447
+ return left.childId === right.childId && left.epoch === right.epoch && sameTarget$1(left.workhorse, right.workhorse);
2448
+ }
2449
+ /**
2450
+ * Copy a target so later changes by the composition root cannot alter a captured operation.
2451
+ * @param target - The live target.
2452
+ * @returns A frozen copy.
2453
+ */
2454
+ function snapshotTarget(target) {
2455
+ return freeze$3({ ...target });
2456
+ }
2457
+ /**
2458
+ * Copy a binding and both of its targets for the lifetime of one operation.
2459
+ * @param binding - The live binding.
2460
+ * @returns A frozen copy with frozen targets.
2461
+ */
2462
+ function snapshotBinding(binding) {
2463
+ return freeze$3({
2464
+ childId: binding.childId,
2465
+ epoch: binding.epoch,
2466
+ coordinator: snapshotTarget(binding.coordinator),
2467
+ workhorse: snapshotTarget(binding.workhorse)
2468
+ });
2469
+ }
2470
+ /**
2471
+ * Copy a coordinator call so the event correlation keeps the call as it was accepted.
2472
+ * @param call - The live call.
2473
+ * @returns A frozen copy.
2474
+ */
2475
+ function snapshotCall(call) {
2476
+ return freeze$3({ ...call });
2477
+ }
2478
+ /**
2479
+ * Resolve the wire RPC an operation will issue, which the durable record must name exactly.
2480
+ * @param operation - The mutating workhorse operation.
2481
+ * @param queueOperation - The queue mutation when the operation goes through the queue.
2482
+ * @param rpcOverride - An explicit RPC when the caller already decided the route.
2483
+ * @returns The RPC method name recorded for the operation.
2484
+ */
2485
+ function operationRpc(operation, queueOperation, rpcOverride) {
2486
+ if (rpcOverride !== void 0) return rpcOverride;
2487
+ if (operation === "delegate_to_workhorse") return "turn/start";
2488
+ if (operation === "steer_workhorse") return "turn/steer";
2489
+ if (queueOperation === void 0) throw new TypeError("queue mutation is required");
2490
+ return `thread/queue/${queueOperation}`;
2491
+ }
2492
+ /**
2493
+ * Refuse caller text that is empty or larger than the input byte budget.
2494
+ * @param value - The caller-supplied text.
2495
+ * @param label - How the text is named in the refusal.
2496
+ * @param allowEmpty - Whether an empty string is acceptable.
2497
+ */
2498
+ function validateBoundedInput(value, label, allowEmpty = false) {
2499
+ if (typeof value !== "string" || !allowEmpty && value.length === 0) throw operationError("invalid_input", `${label} must be nonempty text.`);
2500
+ if (Buffer.byteLength(value, "utf8") > INPUT_LIMIT_BYTES) throw operationError("invalid_input", `${label} must be at most ${INPUT_LIMIT_BYTES} UTF-8 bytes.`);
2501
+ }
2502
+ /**
2503
+ * Choose the operation identity for a mutation: the caller's when the dispatcher already owns
2504
+ * the effect, otherwise a freshly minted one, and prove it is current before any effect.
2505
+ * @param runtime - The operations runtime holding the operation authority.
2506
+ * @param operation - The operation being identified, for the refusal message.
2507
+ * @param candidate - The caller-supplied identity, if any.
2508
+ * @returns The validated identity with its wire serialization.
2509
+ */
2510
+ function selectOperationIdentity(runtime, operation, candidate) {
2511
+ try {
2512
+ const operationId = candidate ?? runtime.options.operation.issuer.mintOperationId();
2513
+ runtime.options.operation.validator.assertCurrentOperationId(operationId);
2514
+ return Object.freeze({
2515
+ operationId,
2516
+ operationIdWire: runtime.options.operation.decoder.serializeOperationId(operationId)
2517
+ });
2518
+ } catch (error) {
2519
+ throw operationError("invalid_input", `A current ${operation} identity was unavailable.`, {
2520
+ operation,
2521
+ cause: error
2522
+ });
2523
+ }
2524
+ }
2525
+ /**
2526
+ * Serialize a thread identity to the wire form used as a map key and in notifications.
2527
+ * @param options - The operation options holding the identity decoder.
2528
+ * @param threadId - The trusted thread identity.
2529
+ * @returns The wire string.
2530
+ */
2531
+ function threadIdWire(options, threadId) {
2532
+ return options.identity.decoder.serializeCodexIdentity(threadId);
2533
+ }
2534
+ /**
2535
+ * Serialize a turn identity to the wire form found in notifications.
2536
+ * @param options - The operation options holding the identity decoder.
2537
+ * @param turnId - The trusted turn identity.
2538
+ * @returns The wire string.
2539
+ */
2540
+ function turnIdWire(options, turnId) {
2541
+ return options.identity.decoder.serializeCodexIdentity(turnId);
2542
+ }
2543
+ /**
2544
+ * Adopt a raw turn identity from a notification through the trusted decoder.
2545
+ * @param options - The operation options holding the identity decoder.
2546
+ * @param value - The raw wire turn identity.
2547
+ * @returns The trusted turn identity.
2548
+ */
2549
+ function turnIdFromRaw(options, value) {
2550
+ const turnId = options.identity.decoder.adoptCodexResponseIdentities({ turnIds: [value] }).turnIds[0];
2551
+ if (turnId === void 0) throw new TypeError("notification did not contain a turn identity");
2552
+ return turnId;
2553
+ }
2554
+ /**
2555
+ * Collect the client identities of the user messages in a turn; they are how a queued or
2556
+ * started submission is matched back to the operation that sent it.
2557
+ * @param turn - The turn from a turn lifecycle notification.
2558
+ * @returns The client identities present on user messages.
2559
+ */
2560
+ function userMessageClientIds(turn) {
2561
+ return turn.items.flatMap((item) => item.type === "userMessage" && item.clientId !== null ? [item.clientId] : []);
2562
+ }
2563
+ /**
2564
+ * Project a queue snapshot to its submission identities.
2565
+ * @param queue - The queue entries.
2566
+ * @returns A frozen list of identities in queue order.
2567
+ */
2568
+ function queueIds(queue) {
2569
+ return freeze$3(queue.map(({ id }) => id));
2570
+ }
2571
+ // src/runtime/workhorses/workhorse-operations/rules/link-provenance.ts
2572
+ const WORKHORSE_CREATION_KIND = "create_thread";
2573
+ const WORKHORSE_THREAD_SOURCE$1 = CODEX_SESSION_THREAD_SOURCE;
2574
+ /**
2575
+ * Check that a durable record's correlation names the target's child, epoch and operation.
2576
+ * @param record - The committed epoch record.
2577
+ * @param target - The operation target.
2578
+ * @returns Whether the correlation matches.
2579
+ */
2580
+ function correlationMatchesTarget(record, target) {
2581
+ return record.correlation.childId === target.childId && record.correlation.epoch === target.epoch && record.correlation.operationId === target.operationId;
2582
+ }
2583
+ /**
2584
+ * Check that a durable record's provenance names the target's thread under the same ownership
2585
+ * and carries a confirmed thread source.
2586
+ * @param record - The committed epoch record.
2587
+ * @param target - The operation target.
2588
+ * @returns Whether the provenance matches.
2589
+ */
2590
+ function provenanceMatchesTarget(record, target) {
2591
+ return record.provenance.childId === target.childId && record.provenance.epoch === target.epoch && record.provenance.threadId === target.threadId && record.provenance.threadSource !== null;
2592
+ }
2593
+ /**
2594
+ * Check that a durable record proves ownership of exactly the operation target.
2595
+ * @param record - The committed epoch record.
2596
+ * @param target - The operation target.
2597
+ * @returns Whether both correlation and provenance match.
2598
+ */
2599
+ function recordMatchesTarget(record, target) {
2600
+ return correlationMatchesTarget(record, target) && provenanceMatchesTarget(record, target);
2601
+ }
2602
+ /**
2603
+ * Check that an executable link still names the captured target.
2604
+ * @param link - The executable link from the classifier.
2605
+ * @param target - The operation target.
2606
+ * @returns Whether child, epoch and thread agree.
2607
+ */
2608
+ function linkMatchesTarget(link, target) {
2609
+ return link.childId === target.childId && link.epoch === target.epoch && link.threadId === target.threadId;
2610
+ }
2611
+ /**
2612
+ * Check that the classification carries a committed, delivered proof for the target.
2613
+ * @param classification - The classified link.
2614
+ * @param target - The operation target.
2615
+ * @returns Whether the proof is present and canonical for the target.
2616
+ */
2617
+ function proofMatchesTarget(classification, target) {
2618
+ const proof = classification.proof;
2619
+ return proof !== null && recordMatchesTarget(proof.record, target) && proof.record.status === "committed" && proof.record.outcome === "delivered";
2620
+ }
2621
+ /**
2622
+ * Refuse any link that is not executable for the exact target with current durable proof.
2623
+ * Mutations run only against a link the classifier and the epoch store both vouch for.
2624
+ * @param classification - The classified link.
2625
+ * @param target - The operation target the link must match.
2626
+ * @param label - How the link is named in the refusal.
2627
+ */
2628
+ function assertExecutableClassification(classification, target, label) {
2629
+ const link = classification.link;
2630
+ if (link.state !== "executable") {
2631
+ const reason = link.reason;
2632
+ throw operationError(mapLinkReason(reason), `${label} is inspect-only: ${reason}. Re-read the current linked state before retrying.`);
2633
+ }
2634
+ if (!linkMatchesTarget(link, target) || !proofMatchesTarget(classification, target)) throw operationError("unknown_provenance", `${label} lost its current executable provenance; inspect the link before retrying.`);
2635
+ }
2636
+ /**
2637
+ * Recognise the workhorse this server created, the only thread whose queue it may touch.
2638
+ * @param classification - The classified workhorse link.
2639
+ * @returns Whether the link is executable, app-server sourced and proven by a creation record.
2640
+ */
2641
+ function isCreatedWorkhorse(classification) {
2642
+ return classification.link.state === "executable" && classification.link.source === WORKHORSE_THREAD_SOURCE$1 && classification.proof?.record.operation.kind === WORKHORSE_CREATION_KIND && classification.proof.record.provenance.threadSource === WORKHORSE_THREAD_SOURCE$1;
2643
+ }
2644
+ /**
2645
+ * Refuse queue access to any thread other than the created, proven workhorse.
2646
+ * @param classification - The classified workhorse link.
2647
+ */
2648
+ function assertCreatedWorkhorse(classification) {
2649
+ if (!isCreatedWorkhorse(classification)) throw operationError("unknown_provenance", "Queue access is restricted to the created workhorse with proven ownership.");
2650
+ }
2651
+ // src/runtime/workhorses/workhorse-operations/operations/inspect.ts
2652
+ /** The longest text an inspection reports for one request or progress entry. */
2653
+ const TEXT_LIMIT = 400;
2654
+ /** The most sub-agents an inspection lists. */
2655
+ const SUB_AGENT_LIMIT = 50;
2656
+ /**
2657
+ * Every thread source. Codex lists only interactive threads when a listing names no source, and
2658
+ * a sub-agent is not one.
2659
+ */
2660
+ const EVERY_SOURCE_KIND = [
2661
+ "cli",
2662
+ "vscode",
2663
+ "exec",
2664
+ "appServer",
2665
+ "subAgent",
2666
+ "subAgentReview",
2667
+ "subAgentCompact",
2668
+ "subAgentThreadSpawn",
2669
+ "subAgentOther",
2670
+ "unknown"
2671
+ ];
2672
+ /**
2673
+ * Cut a text to the inspection's bound.
2674
+ * @param text The text.
2675
+ * @returns The text, or its start with an ellipsis.
2676
+ */
2677
+ function bounded(text) {
2678
+ const trimmed = text.trim();
2679
+ return trimmed.length <= TEXT_LIMIT ? trimmed : `${trimmed.slice(0, 397)}...`;
2680
+ }
2681
+ /**
2682
+ * The text a person or the coordinator sent in one user message.
2683
+ * @param item A turn item.
2684
+ * @returns Its text, or null when the item is no user message with text.
2685
+ */
2686
+ function requestText(item) {
2687
+ if (item.type !== "userMessage") return null;
2688
+ const text = item.content.flatMap((input) => input.type === "text" ? [input.text] : []).join("\n");
2689
+ return text.trim().length === 0 ? null : bounded(text);
2690
+ }
2691
+ /**
2692
+ * What one turn item says the turn did.
2693
+ * @param item A turn item.
2694
+ * @returns A short line, or null for an item that says nothing about progress.
2695
+ */
2696
+ function progressLine(item) {
2697
+ if (item.type === "agentMessage" && item.text.trim().length > 0) return bounded(item.text);
2698
+ if (item.type === "commandExecution") return bounded(`ran ${item.command}`);
2699
+ if (item.type === "plan" && item.text.trim().length > 0) return bounded(`plan: ${item.text}`);
2700
+ return null;
2701
+ }
2702
+ /**
2703
+ * The newest turn of the workhorse thread, with the items Codex keeps in its summary view.
2704
+ * @param runtime The operations runtime.
2705
+ * @param threadId The workhorse thread.
2706
+ * @returns The turn, or null when the thread has none.
2707
+ */
2708
+ async function newestTurn(runtime, threadId) {
2709
+ return (await runtime.options.session.threadTurnsListPage({
2710
+ threadId,
2711
+ limit: 1,
2712
+ sortDirection: "desc",
2713
+ itemsView: "summary"
2714
+ })).data[0] ?? null;
2715
+ }
2716
+ /**
2717
+ * The turn that runs on the workhorse thread now, as Codex lists it.
2718
+ * @param runtime The operations runtime.
2719
+ * @param threadId The workhorse thread.
2720
+ * @returns The running turn, or null when none runs.
2721
+ */
2722
+ async function readActiveTurn(runtime, threadId) {
2723
+ const turn = await newestTurn(runtime, threadId);
2724
+ return turn?.status === "inProgress" ? turn.id : null;
2725
+ }
2726
+ /**
2727
+ * The sub-agents a thread spawned, at any depth, oldest first, so a parent comes before the
2728
+ * agents it spawned.
2729
+ * @param session Lists threads.
2730
+ * @param threadId The thread.
2731
+ * @param limit The most sub-agents to list.
2732
+ * @returns Each sub-agent and its status.
2733
+ */
2734
+ async function listSubAgents(session, threadId, limit = Number.POSITIVE_INFINITY) {
2735
+ const found = [];
2736
+ let cursor = null;
2737
+ do {
2738
+ const page = await session.threadListPage({
2739
+ ancestorThreadId: threadId,
2740
+ sourceKinds: [...EVERY_SOURCE_KIND],
2741
+ sortDirection: "asc",
2742
+ cursor
2743
+ });
2744
+ found.push(...page.data.map((thread) => ({
2745
+ threadId: thread.id,
2746
+ status: thread.status.type
2747
+ })));
2748
+ cursor = page.nextCursor;
2749
+ } while (cursor !== null && found.length < limit);
2750
+ return found.slice(0, limit);
2751
+ }
2752
+ /**
2753
+ * Record the running turn for later notifications, so the operations owner follows it.
2754
+ * @param runtime The operations runtime.
2755
+ * @param threadId The workhorse thread.
2756
+ * @param turnId The running turn, or null.
2757
+ */
2758
+ function noteActiveTurn$1(runtime, threadId, turnId) {
2759
+ const key = threadIdWire(runtime.options, threadId);
2760
+ if (turnId === null) runtime.activeTurns.delete(key);
2761
+ else runtime.activeTurns.set(key, turnId);
2762
+ }
2763
+ /**
2764
+ * The queued requests of a workhorse that this server created and proved; the queue of any other
2765
+ * thread is not this server's to read.
2766
+ * @param runtime The operations runtime.
2767
+ * @param created Whether this server created the workhorse thread.
2768
+ * @param unavailable The reads that failed; added to.
2769
+ * @returns The queued requests.
2770
+ */
2771
+ async function readQueue(runtime, created, unavailable) {
2772
+ if (!created) {
2773
+ unavailable.push("queue");
2774
+ return [];
2775
+ }
2776
+ return runtime.options.queue.list().then((result) => queueIds(result.queue), () => (unavailable.push("queue"), []));
2777
+ }
2778
+ /**
2779
+ * The request and progress a turn's items report.
2780
+ * @param turn The newest turn, or null.
2781
+ * @returns The first request text and the newest progress lines.
2782
+ */
2783
+ function turnStory(turn) {
2784
+ const items = turn?.items ?? [];
2785
+ return {
2786
+ request: items.map(requestText).find((text) => text !== null) ?? null,
2787
+ recentProgress: items.map(progressLine).filter((line) => line !== null).slice(-3)
2788
+ };
2789
+ }
2790
+ /**
2791
+ * Create the inspect operation: a read of the link, the running turn, its request and progress,
2792
+ * the sub-agents and the queue, which never mutates anything.
2793
+ * @param runtime The operations runtime.
2794
+ * @returns The inspect operation.
2795
+ */
2796
+ function createInspect(runtime) {
2797
+ return (request) => runtime.enqueue(async () => {
2798
+ const binding = runtime.currentBinding();
2799
+ const { threadId } = binding.workhorse;
2800
+ const initial = await runtime.classify(binding, request.call, "inspect_workhorse");
2801
+ const unavailable = [];
2802
+ const [turn, agents, queue] = await Promise.all([
2803
+ newestTurn(runtime, threadId).catch(() => (unavailable.push("turns"), null)),
2804
+ listSubAgents(runtime.options.session, threadId, SUB_AGENT_LIMIT).catch(() => (unavailable.push("subAgents"), [])),
2805
+ readQueue(runtime, isCreatedWorkhorse(initial.workhorse), unavailable)
2806
+ ]);
2807
+ const final = await runtime.classify(binding, request.call, "inspect_workhorse");
2808
+ const activeTurnId = turn?.status === "inProgress" ? turn.id : null;
2809
+ noteActiveTurn$1(runtime, threadId, activeTurnId);
2810
+ return freeze$3({
2811
+ threadId,
2812
+ status: final.workhorse.link.status,
2813
+ activeTurnId,
2814
+ ...turnStory(turn),
2815
+ subAgents: agents,
2816
+ queuedSubmissionIds: queue,
2817
+ unavailable: unavailable.toSorted()
2818
+ });
2819
+ });
2820
+ }
2821
+ // src/server/sessions/services/work-tree-reads.ts
2822
+ /**
2823
+ * The turn running on a thread that Codex reports as active, from its newest turns. A thread
2824
+ * summary carries no turns, so only this listing names the running turn.
2825
+ * @param session Lists turns.
2826
+ * @param threadId The thread.
2827
+ * @returns The running turn, or "unknown" when no listed turn is in progress.
2828
+ */
2829
+ async function runningTurn(session, threadId) {
2830
+ return (await session.threadTurnsListPage({
2831
+ threadId,
2832
+ limit: 5,
2833
+ sortDirection: "desc",
2834
+ itemsView: "notLoaded"
2835
+ })).data.find((turn) => turn.status === "inProgress")?.id ?? "unknown";
2836
+ }
2837
+ /**
2838
+ * Every request waiting in a thread's queue.
2839
+ * @param session Lists queues.
2840
+ * @param threadId The thread.
2841
+ * @returns The queued requests, in queue order.
2842
+ * @throws {Error} When Codex repeats a cursor, so the listing would never end.
2843
+ */
2844
+ async function queuedRequests(session, threadId) {
2845
+ const ids = [];
2846
+ const seen = /* @__PURE__ */ new Set();
2847
+ let cursor = null;
2848
+ do {
2849
+ const page = await session.queueListPage({
2850
+ threadId,
2851
+ cursor
2852
+ });
2853
+ ids.push(...page.data.map((submission) => submission.id));
2854
+ cursor = page.nextCursor;
2855
+ if (cursor !== null && seen.has(cursor)) throw new Error("The queue listing repeated a cursor.");
2856
+ if (cursor !== null) seen.add(cursor);
2857
+ } while (cursor !== null);
2858
+ return ids;
2859
+ }
2860
+ /**
2861
+ * The turn running on a thread now, read again after its empty queue was listed: a request that
2862
+ * left the queue while it was listed started a turn that the first status read could not see.
2863
+ * @param session Reads threads and turns.
2864
+ * @param threadId The thread.
2865
+ * @returns What the thread runs; a read that fails leaves the thread unread.
2866
+ */
2867
+ async function readAgain(session, threadId) {
2868
+ const status = await session.threadRead({
2869
+ threadId,
2870
+ includeTurns: false
2871
+ }).then(({ thread }) => thread.status.type).catch(() => null);
2872
+ if (status === null) return {
2873
+ threadId,
2874
+ running: null,
2875
+ queued: null
2876
+ };
2877
+ return {
2878
+ threadId,
2879
+ running: status === "active" ? await runningTurn(session, threadId).catch(() => "unknown") : null,
2880
+ queued: []
2881
+ };
2882
+ }
2883
+ /**
2884
+ * Observe one thread whose status is known. A thread that is not loaded runs nothing and starts
2885
+ * nothing until something loads it, so its queue is not read. A thread that ran nothing and whose
2886
+ * queue was empty is read once more.
2887
+ * @param session Reads turns and queues.
2888
+ * @param threadId The thread.
2889
+ * @param status Its status type as Codex reported it.
2890
+ * @returns What it runs and what waits on it; a read that fails reads as unknown.
2891
+ */
2892
+ async function observeThread(session, threadId, status) {
2893
+ if (status === "notLoaded") return {
2894
+ threadId,
2895
+ running: null,
2896
+ queued: []
2897
+ };
2898
+ const [running, queued] = await Promise.all([status === "active" ? runningTurn(session, threadId).catch(() => "unknown") : Promise.resolve(null), queuedRequests(session, threadId).catch(() => null)]);
2899
+ return running === null && queued?.length === 0 ? readAgain(session, threadId) : {
2900
+ threadId,
2901
+ running,
2902
+ queued
2903
+ };
2904
+ }
2905
+ // src/server/sessions/services/stop.ts
2906
+ /** The clock of a running server. */
2907
+ const SYSTEM_CLOCK = Object.freeze({
2908
+ /**
2909
+ * The time now.
2910
+ * @returns Milliseconds since the epoch.
2911
+ */
2912
+ now: () => Date.now(),
2913
+ /**
2914
+ * Wait.
2915
+ * @param ms How long.
2916
+ */
2917
+ wait: async (ms) => {
2918
+ await new Promise((resolve) => {
2919
+ setTimeout(resolve, ms);
2920
+ });
2921
+ }
2922
+ });
2923
+ /**
2924
+ * The refusal of new work for a workhorse that is stopping, or whose stop did not end all work,
2925
+ * or whose stop the asking coordinator turn requested. Its code is a reviewed tool refusal
2926
+ * reason, so the coordinator hears it as busy.
2927
+ */
2928
+ var WorkhorseStopRefusal = class extends Error {
2929
+ name = "WorkhorseStopRefusal";
2930
+ code = "busy";
2931
+ };
2932
+ /**
2933
+ * Read the whole work tree once: the workhorse thread first, then each sub-agent, parents before
2934
+ * the agents they spawned.
2935
+ * @param session Reads threads, turns and queues.
2936
+ * @param root The workhorse thread.
2937
+ * @returns What the pass saw.
2938
+ */
2939
+ async function readTree(session, root) {
2940
+ const [rootThread, agents] = await Promise.all([session.threadRead({
2941
+ threadId: root,
2942
+ includeTurns: false
2943
+ }).then(({ thread }) => observeThread(session, root, thread.status.type)).catch(() => ({
2944
+ threadId: root,
2945
+ running: null,
2946
+ queued: null
2947
+ })), listSubAgents(session, root).catch(() => null)]);
2948
+ return {
2949
+ threads: [rootThread, ...await Promise.all((agents ?? []).map(({ threadId, status }) => observeThread(session, threadId, status)))],
2950
+ listed: agents !== null
2951
+ };
2952
+ }
2953
+ /**
2954
+ * What one thread still runs, waits on or hides.
2955
+ * @param thread What a pass saw of it.
2956
+ * @returns Its remaining work, or null when it has none.
2957
+ */
2958
+ function remainingOn(thread) {
2959
+ if (thread.running !== null) return {
2960
+ threadId: thread.threadId,
2961
+ state: "running"
2962
+ };
2963
+ if (thread.queued === null) return {
2964
+ threadId: thread.threadId,
2965
+ state: "unread"
2966
+ };
2967
+ return thread.queued.length > 0 ? {
2968
+ threadId: thread.threadId,
2969
+ state: "queued"
2970
+ } : null;
2971
+ }
2972
+ /**
2973
+ * What a pass saw that still runs, waits or could not be read. A sub-agent listing that failed
2974
+ * leaves the workhorse thread unread, because its tree is unknown.
2975
+ * @param tree What the pass saw.
2976
+ * @returns The remaining work.
2977
+ */
2978
+ function remainingOf(tree) {
2979
+ const remaining = tree.threads.flatMap((thread) => remainingOn(thread) ?? []);
2980
+ const root = tree.threads[0].threadId;
2981
+ return tree.listed || remaining.some((work) => work.threadId === root) ? remaining : [{
2982
+ threadId: root,
2983
+ state: "unread"
2984
+ }, ...remaining];
2985
+ }
2986
+ /**
2987
+ * Delete what waits on one thread and interrupt what runs on it. A turn is interrupted once; a
2988
+ * turn that starts later is a new turn. A failed effect is not an outcome: the next pass reads
2989
+ * what became of it.
2990
+ * @param session Deletes queued requests and interrupts turns.
2991
+ * @param thread What the pass saw of the thread.
2992
+ * @param interrupted The turns already interrupted by this stop; added to.
2993
+ */
2994
+ async function stopThread(session, thread, interrupted) {
2995
+ await Promise.all((thread.queued ?? []).map((queuedSubmissionId) => session.queueDelete({
2996
+ threadId: thread.threadId,
2997
+ queuedSubmissionId
2998
+ }).catch(() => void 0)));
2999
+ const turnId = thread.running;
3000
+ if (turnId === null || turnId === "unknown" || interrupted.has(turnId)) return;
3001
+ interrupted.add(turnId);
3002
+ await session.turnInterrupt({
3003
+ threadId: thread.threadId,
3004
+ turnId
3005
+ }).catch(() => void 0);
3006
+ }
3007
+ /**
3008
+ * Stop every thread a pass saw, the workhorse first and each parent before the agents it spawned,
3009
+ * so no agent is left to spawn again after its children stopped.
3010
+ * @param session Deletes queued requests and interrupts turns.
3011
+ * @param tree What the pass saw.
3012
+ * @param interrupted The turns already interrupted by this stop; added to.
3013
+ */
3014
+ async function act(session, tree, interrupted) {
3015
+ for (const thread of tree.threads) await stopThread(session, thread, interrupted);
3016
+ }
3017
+ /**
3018
+ * The outcome of a stop that ran out of time with work remaining.
3019
+ * @param remaining What still runs, waits or could not be read.
3020
+ * @returns Partial when something was seen running or waiting, otherwise unconfirmed.
3021
+ */
3022
+ function unsettledOutcome(remaining) {
3023
+ return remaining.some((work) => work.state !== "unread") ? "partial" : "unconfirmed";
3024
+ }
3025
+ /**
3026
+ * What a stop ended with, naming at most the threads a report holds.
3027
+ * @param checkout The workhorse's checkout.
3028
+ * @param outcome The outcome, judged from all the remaining work.
3029
+ * @param remaining All the remaining work.
3030
+ * @returns The stop.
3031
+ */
3032
+ function stopOf(checkout, outcome, remaining) {
3033
+ return {
3034
+ checkout,
3035
+ outcome,
3036
+ remaining: remaining.slice(0, 100)
3037
+ };
3038
+ }
3039
+ /**
3040
+ * What a stop ended with when two reads in a row saw nothing left.
3041
+ * @param checkout The workhorse's checkout.
3042
+ * @param acted Whether a pass stopped any work.
3043
+ * @returns Stopped when the stop ended work, otherwise idle.
3044
+ */
3045
+ function ended(checkout, acted) {
3046
+ return stopOf(checkout, acted ? "stopped" : "idle", []);
3047
+ }
3048
+ /**
3049
+ * Stop one work tree: repeat a pass until two reads in a row see nothing that runs, waits or is
3050
+ * unread, or the settle time runs out. Success always comes from a read after the last effect,
3051
+ * and the first pass that sees work always acts on it, however long its read took.
3052
+ * @param checkout The workhorse's checkout.
3053
+ * @param root The workhorse thread.
3054
+ * @param session Reads and stops the tree.
3055
+ * @param clock Tells time and waits between passes.
3056
+ * @returns What the stop observed.
3057
+ */
3058
+ async function settle(checkout, root, session, clock) {
3059
+ const deadline = clock.now() + CODEX_SESSION_MS.workTreeStopSettle;
3060
+ const interrupted = /* @__PURE__ */ new Set();
3061
+ let acted = false;
3062
+ let confirming = false;
3063
+ for (;;) {
3064
+ const tree = await readTree(session, root);
3065
+ const remaining = remainingOf(tree);
3066
+ if (remaining.length === 0) {
3067
+ if (confirming) return ended(checkout, acted);
3068
+ confirming = true;
3069
+ continue;
3070
+ }
3071
+ confirming = false;
3072
+ if (acted && clock.now() >= deadline) return stopOf(checkout, unsettledOutcome(remaining), remaining);
3073
+ await act(session, tree, interrupted);
3074
+ acted = true;
3075
+ await clock.wait(CODEX_SESSION_MS.workTreeStopPoll);
3076
+ }
3077
+ }
3078
+ /**
3079
+ * What one stop of a workhorse observed, whether or not it has a thread.
3080
+ * @param workhorse The workhorse.
3081
+ * @param session Reads and stops its threads.
3082
+ * @param clock Tells time and waits between passes.
3083
+ * @returns What the stop observed; a stop that failed outright is unconfirmed.
3084
+ */
3085
+ function observeStop(workhorse, session, clock) {
3086
+ const { checkout } = workhorse;
3087
+ const root = workhorse.components.workhorse.snapshot().threadId;
3088
+ if (root === null) return Promise.resolve({
3089
+ checkout,
3090
+ outcome: "idle",
3091
+ remaining: []
3092
+ });
3093
+ return settle(checkout, root, session, clock).catch(() => ({
3094
+ checkout,
3095
+ outcome: "unconfirmed",
3096
+ remaining: [{
3097
+ threadId: root,
3098
+ state: "unread"
3099
+ }]
3100
+ }));
3101
+ }
3102
+ /**
3103
+ * Stop a workhorse's whole work tree. A stop that is already running answers this one too.
3104
+ * @param workhorse The workhorse.
3105
+ * @param session Reads and stops its threads.
3106
+ * @param askedBy The coordinator turn that asked for the stop, or null for the Stop control.
3107
+ * @param clock Tells time and waits between passes.
3108
+ * @returns What the stop observed.
3109
+ */
3110
+ async function stopWorkTree(workhorse, session, askedBy, clock = SYSTEM_CLOCK) {
3111
+ const { state } = workhorse;
3112
+ if (askedBy !== null) state.stopAskers.add(askedBy);
3113
+ if (state.stop?.kind === "stopping") return state.stop.done;
3114
+ const admitted = [...state.admitted];
3115
+ const done = Promise.all(admitted).then(() => observeStop(workhorse, session, clock));
3116
+ state.stop = {
3117
+ kind: "stopping",
3118
+ done
3119
+ };
3120
+ const stop = await done;
3121
+ state.stop = phaseAfter(stop);
3122
+ return stop;
3123
+ }
3124
+ /**
3125
+ * Where a workhorse stands after a stop.
3126
+ * @param stop What the stop observed.
3127
+ * @returns Stopped when it showed that all work ended, otherwise unresolved.
3128
+ */
3129
+ function phaseAfter(stop) {
3130
+ return stop.outcome === "stopped" || stop.outcome === "idle" ? {
3131
+ kind: "stopped",
3132
+ stop
3133
+ } : {
3134
+ kind: "unresolved",
3135
+ stop
3136
+ };
3137
+ }
3138
+ /**
3139
+ * Whether a coordinator turn asked for a stop of a workhorse.
3140
+ * @param workhorse The workhorse.
3141
+ * @param coordinatorTurn The coordinator turn starting work, or null for a person's request.
3142
+ * @returns True only for a coordinator turn that asked for a stop.
3143
+ */
3144
+ function askedForStop(workhorse, coordinatorTurn) {
3145
+ return coordinatorTurn !== null && workhorse.state.stopAskers.has(coordinatorTurn);
3146
+ }
3147
+ /**
3148
+ * Why a workhorse takes no new work now.
3149
+ * @param workhorse The workhorse.
3150
+ * @param coordinatorTurn The coordinator turn starting the work, or null for a person's request.
3151
+ * @returns The reason, or null when it takes the work.
3152
+ */
3153
+ function refusal$3(workhorse, coordinatorTurn) {
3154
+ const { checkout, state } = workhorse;
3155
+ const phase = state.stop;
3156
+ switch (phase?.kind) {
3157
+ case "stopping": return `The workhorse of ${checkout} is stopping; new work waits until the stop ends.`;
3158
+ case "unresolved": return `The last stop of the workhorse of ${checkout} did not show that all work ended (${phase.stop.outcome}); inspect it or stop it again before new work.`;
3159
+ default: return askedForStop(workhorse, coordinatorTurn) ? `The work of ${checkout} stopped at the user's request; start work again only for a new request from the user.` : null;
3160
+ }
3161
+ }
3162
+ /**
3163
+ * Refuse new work for a workhorse that is stopping or whose stop did not end all work, and work
3164
+ * that the coordinator turn which asked for a finished stop tries to start.
3165
+ * @param workhorse The workhorse the work is for.
3166
+ * @param coordinatorTurn The coordinator turn starting the work, or null for a person's request.
3167
+ * @throws {WorkhorseStopRefusal} When the workhorse takes no new work now.
3168
+ */
3169
+ function refuseWhileStopping(workhorse, coordinatorTurn) {
3170
+ const reason = refusal$3(workhorse, coordinatorTurn);
3171
+ if (reason !== null) throw new WorkhorseStopRefusal(reason);
3172
+ }
3173
+ /**
3174
+ * Start work on a workhorse unless it refuses work now, and hold the work as admitted until it
3175
+ * settles, so a stop that begins meanwhile waits for it and then sees what it started.
3176
+ * @param workhorse The workhorse the work is for.
3177
+ * @param coordinatorTurn The coordinator turn starting the work, or null for a person's request.
3178
+ * @param start The work.
3179
+ * @returns What the work returned.
3180
+ * @throws {WorkhorseStopRefusal} When the workhorse takes no new work now.
3181
+ */
3182
+ function admitWork(workhorse, coordinatorTurn, start) {
3183
+ refuseWhileStopping(workhorse, coordinatorTurn);
3184
+ const running = start();
3185
+ const settled = running.then(() => void 0, () => void 0);
3186
+ workhorse.state.admitted.add(settled);
3187
+ settled.then(() => workhorse.state.admitted.delete(settled));
3188
+ return running;
3189
+ }
3190
+ /**
3191
+ * A workhorse's owners and actions, with every entry that starts work refusing it while the
3192
+ * workhorse stops, after a stop that did not end all its work, and from the coordinator turn that
3193
+ * asked for a stop that ended it. Deleting, reordering and editing what waits stay open, and so do
3194
+ * reads and the stop itself.
3195
+ * @param workhorse The workhorse, once it is built.
3196
+ * @param built Its owners and actions as its builder made them.
3197
+ * @returns The same owners and actions, guarded.
3198
+ */
3199
+ function guardWorkhorse(workhorse, built) {
3200
+ const { queue, operations } = built.components;
3201
+ const { threadLinks, ensureStarted } = built.actions;
3202
+ /**
3203
+ * Run one entry that starts work, unless the workhorse refuses it now.
3204
+ * @param coordinatorTurn The coordinator turn asking, or null for a person's request.
3205
+ * @param start The entry.
3206
+ * @returns What the entry returned.
3207
+ */
3208
+ const guarded = async (coordinatorTurn, start) => admitWork(workhorse(), coordinatorTurn, start);
3209
+ return {
3210
+ components: {
3211
+ ...built.components,
3212
+ queue: {
3213
+ ...queue,
3214
+ /**
3215
+ * Queue a prompt, as the browser and explanations do.
3216
+ * @param request The prompt.
3217
+ * @returns The queue's answer.
3218
+ */
3219
+ add: (request) => guarded(null, () => queue.add(request)),
3220
+ /**
3221
+ * Run a queued prompt now.
3222
+ * @param request The prompt.
3223
+ * @returns The queue's answer.
3224
+ */
3225
+ start: (request) => guarded(null, () => queue.start(request))
3226
+ },
3227
+ operations: {
3228
+ ...operations,
3229
+ /**
3230
+ * Give the workhorse work for the coordinator.
3231
+ * @param request The work.
3232
+ * @returns The operation's answer.
3233
+ */
3234
+ delegate: (request) => guarded(request.call.turnId, () => operations.delegate(request)),
3235
+ /**
3236
+ * Steer the running turn for the coordinator.
3237
+ * @param request The steer.
3238
+ * @returns The operation's answer.
3239
+ */
3240
+ steer: (request) => guarded(request.call.turnId, () => operations.steer(request)),
3241
+ /**
3242
+ * Change the queue for the coordinator; only adding and starting is new work.
3243
+ * @param request The change.
3244
+ * @returns The operation's answer.
3245
+ */
3246
+ manageQueue: (request) => request.operation === "add" || request.operation === "start" ? guarded(request.call.turnId, () => operations.manageQueue(request)) : operations.manageQueue(request)
3247
+ }
3248
+ },
3249
+ actions: {
3250
+ threadLinks: {
3251
+ /**
3252
+ * Start a new conversation of the workhorse.
3253
+ * @param command The creation.
3254
+ * @param context The chat.
3255
+ * @returns The link owner's answer.
3256
+ */
3257
+ create: (command, context) => guarded(null, () => threadLinks.create(command, context)) },
3258
+ /**
3259
+ * Start the workhorse's thread when it has none, as a delegation does.
3260
+ * @returns When it has one.
3261
+ */
3262
+ ensureStarted: () => guarded(null, ensureStarted)
3263
+ }
3264
+ };
3265
+ }
3266
+ /**
3267
+ * Where a workhorse's last stop stands, as inspection reports it.
3268
+ * @param workhorse The workhorse.
3269
+ * @returns Stopping while it runs, then what it observed; null before any stop.
3270
+ */
3271
+ function stopReport(workhorse) {
3272
+ const phase = workhorse.state.stop;
3273
+ if (phase === null) return null;
3274
+ if (phase.kind === "stopping") return {
3275
+ outcome: "stopping",
3276
+ remaining: []
3277
+ };
3278
+ return {
3279
+ outcome: phase.stop.outcome,
3280
+ remaining: [...phase.stop.remaining]
3281
+ };
3282
+ }
1746
3283
  // src/runtime/approvals/services/contract.ts
1747
3284
  var CodexApprovalError = class extends Error {
1748
3285
  name = "CodexApprovalError";
@@ -5475,6 +7012,7 @@ function errorOutcome(error) {
5475
7012
  */
5476
7013
  function errorCode(error) {
5477
7014
  if (error instanceof CodexWorkbenchGatewayError) return error.code;
7015
+ if (error instanceof WorkhorseStopRefusal) return "work_stopping";
5478
7016
  return errorOutcome(error) === "outcome_unknown" ? "outcome_unknown" : "command_failed";
5479
7017
  }
5480
7018
  /** What each refusal code says to the browser, in words a person can act on. */
@@ -5494,7 +7032,9 @@ const REFUSAL_MESSAGES = {
5494
7032
  child_disconnected: "The Codex child disconnected; inspect state before retrying.",
5495
7033
  approval_not_pending: "That approval is no longer pending.",
5496
7034
  dynamic_approval_not_pending: "That coordination approval is no longer pending.",
5497
- unsupported_command: "The browser command is not supported by this gateway."
7035
+ unsupported_command: "The browser command is not supported by this gateway.",
7036
+ work_stopping: "The workhorse is stopping, or its last stop did not show that all work ended. Before you send new work, press Stop while it shows, or ask the voice coordinator to stop the work.",
7037
+ stop_unconfirmed: "Some work of this workhorse or its sub-agents still runs or could not be read. Press Stop again while it shows, or ask the voice coordinator to stop the work."
5498
7038
  };
5499
7039
  /**
5500
7040
  * What a command result says, which is fixed text per outcome and code: the
@@ -7820,6 +9360,10 @@ const DEFAULT_SETTINGS = [
7820
9360
  {
7821
9361
  key: "sandbox_workspace_write",
7822
9362
  line: "sandbox_workspace_write.network_access = true"
9363
+ },
9364
+ {
9365
+ key: "experimental_realtime_ws_model",
9366
+ line: "experimental_realtime_ws_model = \"gpt-live-1.1-codex\""
7823
9367
  }
7824
9368
  ];
7825
9369
  /**
@@ -7958,7 +9502,9 @@ function completedConfig(existing, sqliteHome, fileSystem, configPath) {
7958
9502
  const parsed = parsedToml(existing);
7959
9503
  if (parsed === void 0) throw failure$1("config_conflict", configPath, `Codex config ${configPath} is not valid TOML. Refusing to overwrite it.`);
7960
9504
  const withHome = withSqliteHome(existing, parsed["sqlite_home"], sqliteHome, fileSystem, configPath);
7961
- return `${DEFAULT_SETTINGS.filter(({ key }) => !Object.hasOwn(parsed, key)).map(({ line }) => `${line}\n`).join("")}${withHome}`;
9505
+ const defaults = DEFAULT_SETTINGS.filter(({ key }) => !Object.hasOwn(parsed, key)).map(({ line }) => `${line}\n`).join("");
9506
+ const insertion = firstLineSqliteHome(withHome) === void 0 ? 0 : withHome.indexOf("\n") + 1;
9507
+ return `${withHome.slice(0, insertion)}${defaults}${withHome.slice(insertion)}`;
7962
9508
  }
7963
9509
  /**
7964
9510
  * Parse TOML text into a table.
@@ -11242,7 +12788,7 @@ function isTerminal(state) {
11242
12788
  * @param right - The other binding.
11243
12789
  * @returns True when they are the same binding.
11244
12790
  */
11245
- function sameBinding$4(left, right) {
12791
+ function sameBinding$3(left, right) {
11246
12792
  return left.child === right.child && left.epoch === right.epoch && left.link === right.link && left.target === right.target && left.effect === right.effect;
11247
12793
  }
11248
12794
  /**
@@ -11464,7 +13010,7 @@ function createApprovalViews(context) {
11464
13010
  reason: "not_pending"
11465
13011
  };
11466
13012
  const live = context.currentBinding(record);
11467
- return spokenEligibility(record.request, live !== null && sameBinding$4(live, record.request.binding), serverFacts(context, record), record.spokenEffectPresentation);
13013
+ return spokenEligibility(record.request, live !== null && sameBinding$3(live, record.request.binding), serverFacts(context, record), record.spokenEffectPresentation);
11468
13014
  };
11469
13015
  /**
11470
13016
  * The owner's view of one approval: its request, its snapshot, whether it can be spoken, and
@@ -12025,7 +13571,7 @@ function rebindApprovalRequest(request, input) {
12025
13571
  function bindingEvidenceMatches(record, input) {
12026
13572
  if (input.binding === void 0) return true;
12027
13573
  try {
12028
- return sameBinding$4(record.request.binding, completeBinding(record.request, input.binding));
13574
+ return sameBinding$3(record.request.binding, completeBinding(record.request, input.binding));
12029
13575
  } catch {
12030
13576
  return false;
12031
13577
  }
@@ -12054,7 +13600,7 @@ function claimTerminal(record, terminalDelivery) {
12054
13600
  * @returns The state, reason and response to settle with.
12055
13601
  */
12056
13602
  function provenSettlement(record, liveBinding, requested) {
12057
- if (liveBinding !== null && sameBinding$4(liveBinding, record.request.binding)) return requested;
13603
+ if (liveBinding !== null && sameBinding$3(liveBinding, record.request.binding)) return requested;
12058
13604
  return {
12059
13605
  state: "stale",
12060
13606
  reason: "The approval target or effect is stale; visual fallback was sent.",
@@ -19711,7 +21257,7 @@ function afterAttemptReason$1(callback, options, disposed) {
19711
21257
  * @param value - The value to freeze.
19712
21258
  * @returns The same value, frozen.
19713
21259
  */
19714
- function freeze$3(value) {
21260
+ function freeze$2(value) {
19715
21261
  return Object.freeze(value);
19716
21262
  }
19717
21263
  /**
@@ -19733,7 +21279,7 @@ function makeDelivery(callback, evidence, input) {
19733
21279
  kind: deliveryKind(),
19734
21280
  callback,
19735
21281
  sourceOrder: evidence.sourceOrder,
19736
- freshness: freeze$3({
21282
+ freshness: freeze$2({
19737
21283
  capturedAtMs: evidence.capturedAtMs,
19738
21284
  freshUntilMs: evidence.freshUntilMs
19739
21285
  }),
@@ -19742,12 +21288,12 @@ function makeDelivery(callback, evidence, input) {
19742
21288
  text: input.text ?? null,
19743
21289
  realtimeRequest: input.realtimeRequest ?? null
19744
21290
  };
19745
- return input.attemptedAtMs === null ? freeze$3({
21291
+ return input.attemptedAtMs === null ? freeze$2({
19746
21292
  ...shared,
19747
21293
  attempted: false,
19748
21294
  attemptedAtMs: null,
19749
21295
  outcome: "not_delivered"
19750
- }) : freeze$3({
21296
+ }) : freeze$2({
19751
21297
  ...shared,
19752
21298
  attempted: true,
19753
21299
  attemptedAtMs: input.attemptedAtMs,
@@ -19818,17 +21364,17 @@ const VOICE_PATHS = Object.freeze({
19818
21364
  function voiceRequest(append) {
19819
21365
  const { generation, text } = append;
19820
21366
  const threadId = generation.coordinatorThreadId;
19821
- return append.channel === "speech" ? freeze$3({
21367
+ return append.channel === "speech" ? freeze$2({
19822
21368
  generation,
19823
21369
  channel: "speech",
19824
- params: freeze$3({
21370
+ params: freeze$2({
19825
21371
  threadId,
19826
21372
  text
19827
21373
  })
19828
- }) : freeze$3({
21374
+ }) : freeze$2({
19829
21375
  generation,
19830
21376
  channel: "context",
19831
- params: freeze$3({
21377
+ params: freeze$2({
19832
21378
  threadId,
19833
21379
  text,
19834
21380
  role: "developer"
@@ -20160,7 +21706,7 @@ function createSettledLedger(limit) {
20160
21706
  * @param value - The value to freeze.
20161
21707
  * @returns The same value, frozen.
20162
21708
  */
20163
- function freeze$2(value) {
21709
+ function freeze$1(value) {
20164
21710
  return Object.freeze(value);
20165
21711
  }
20166
21712
  /**
@@ -20169,7 +21715,7 @@ function freeze$2(value) {
20169
21715
  * @returns The frozen copy.
20170
21716
  */
20171
21717
  function freezeArray(values) {
20172
- return freeze$2([...values]);
21718
+ return freeze$1([...values]);
20173
21719
  }
20174
21720
  /**
20175
21721
  * Copy the coordinator's logical tool call, which is flat and needs no deep clone.
@@ -20177,7 +21723,7 @@ function freezeArray(values) {
20177
21723
  * @returns The frozen copy.
20178
21724
  */
20179
21725
  function copyCall(value) {
20180
- return freeze$2({ ...value });
21726
+ return freeze$1({ ...value });
20181
21727
  }
20182
21728
  /**
20183
21729
  * Carry the queue operation through unchanged; it is a string literal or null, so there is nothing to copy.
@@ -20210,7 +21756,7 @@ function contextKind() {
20210
21756
  */
20211
21757
  function operationCorrelation(event, workhorseLink, realtimeGeneration) {
20212
21758
  const value = event.correlation;
20213
- return freeze$2({
21759
+ return freeze$1({
20214
21760
  operationId: value.operationId,
20215
21761
  childId: value.childId,
20216
21762
  epoch: value.epoch,
@@ -20223,7 +21769,7 @@ function operationCorrelation(event, workhorseLink, realtimeGeneration) {
20223
21769
  realtimeSessionId: null,
20224
21770
  coordinatorCall: copyCall(value.coordinatorCall),
20225
21771
  workhorseLink: cloneAndFreeze$3(workhorseLink),
20226
- realtimeGeneration: realtimeGeneration === null ? null : freeze$2({ ...realtimeGeneration })
21772
+ realtimeGeneration: realtimeGeneration === null ? null : freeze$1({ ...realtimeGeneration })
20227
21773
  });
20228
21774
  }
20229
21775
  /**
@@ -20253,27 +21799,27 @@ function operationBase(event, workhorseLink, realtimeGeneration) {
20253
21799
  * @returns The frozen operation callback.
20254
21800
  */
20255
21801
  function deliveredOperationCallback(base, type) {
20256
- if (type === "queued") return freeze$2({
21802
+ if (type === "queued") return freeze$1({
20257
21803
  ...base,
20258
21804
  type: "queued",
20259
21805
  outcome: "delivered"
20260
21806
  });
20261
- if (type === "started") return freeze$2({
21807
+ if (type === "started") return freeze$1({
20262
21808
  ...base,
20263
21809
  type: "started",
20264
21810
  outcome: "delivered"
20265
21811
  });
20266
- if (type === "progress") return freeze$2({
21812
+ if (type === "progress") return freeze$1({
20267
21813
  ...base,
20268
21814
  type: "progress",
20269
21815
  outcome: "delivered"
20270
21816
  });
20271
- if (type === "attention") return freeze$2({
21817
+ if (type === "attention") return freeze$1({
20272
21818
  ...base,
20273
21819
  type: "attention",
20274
21820
  outcome: "delivered"
20275
21821
  });
20276
- return freeze$2({
21822
+ return freeze$1({
20277
21823
  ...base,
20278
21824
  type: "completed",
20279
21825
  outcome: "delivered"
@@ -20288,17 +21834,17 @@ function deliveredOperationCallback(base, type) {
20288
21834
  */
20289
21835
  function normalizeOperationCallback(event, workhorseLink, realtimeGeneration) {
20290
21836
  const base = operationBase(event, workhorseLink, realtimeGeneration);
20291
- if (event.type === "failed") return freeze$2({
21837
+ if (event.type === "failed") return freeze$1({
20292
21838
  ...base,
20293
21839
  type: "failed",
20294
21840
  outcome: event.outcome
20295
21841
  });
20296
- if (event.type === "accepted") return freeze$2({
21842
+ if (event.type === "accepted") return freeze$1({
20297
21843
  ...base,
20298
21844
  type: "accepted",
20299
21845
  outcome: "pending"
20300
21846
  });
20301
- if (event.type === "outcome_unknown") return freeze$2({
21847
+ if (event.type === "outcome_unknown") return freeze$1({
20302
21848
  ...base,
20303
21849
  type: "outcome_unknown",
20304
21850
  outcome: "outcome_unknown"
@@ -20313,7 +21859,7 @@ function normalizeOperationCallback(event, workhorseLink, realtimeGeneration) {
20313
21859
  * @returns The frozen correlation.
20314
21860
  */
20315
21861
  function contextCorrelation(event, workhorseLink, realtimeGeneration) {
20316
- return freeze$2({
21862
+ return freeze$1({
20317
21863
  operationId: null,
20318
21864
  childId: event.child.id,
20319
21865
  epoch: event.child.epoch,
@@ -20326,7 +21872,7 @@ function contextCorrelation(event, workhorseLink, realtimeGeneration) {
20326
21872
  realtimeSessionId: event.coordinator.realtimeSessionId,
20327
21873
  coordinatorCall: null,
20328
21874
  workhorseLink: cloneAndFreeze$3(workhorseLink),
20329
- realtimeGeneration: realtimeGeneration === null ? null : freeze$2({ ...realtimeGeneration })
21875
+ realtimeGeneration: realtimeGeneration === null ? null : freeze$1({ ...realtimeGeneration })
20330
21876
  });
20331
21877
  }
20332
21878
  /**
@@ -20337,7 +21883,7 @@ function contextCorrelation(event, workhorseLink, realtimeGeneration) {
20337
21883
  * @returns The frozen callback.
20338
21884
  */
20339
21885
  function normalizeContextCallback(event, workhorseLink, realtimeGeneration) {
20340
- return freeze$2({
21886
+ return freeze$1({
20341
21887
  kind: contextKind(),
20342
21888
  audience: event.audience,
20343
21889
  correlation: contextCorrelation(event, workhorseLink, realtimeGeneration),
@@ -20354,12 +21900,12 @@ function normalizeContextCallback(event, workhorseLink, realtimeGeneration) {
20354
21900
  * @returns The frozen callback.
20355
21901
  */
20356
21902
  function normalizeWorkhorseNewsCallback(event, workhorseLink, realtimeGeneration) {
20357
- return freeze$2({
21903
+ return freeze$1({
20358
21904
  kind: "workhorse_news",
20359
21905
  type: event.type,
20360
21906
  sequence: event.sequence,
20361
21907
  detail: event.detail,
20362
- correlation: freeze$2({
21908
+ correlation: freeze$1({
20363
21909
  operationId: null,
20364
21910
  childId: event.childId,
20365
21911
  epoch: event.epoch,
@@ -20372,7 +21918,7 @@ function normalizeWorkhorseNewsCallback(event, workhorseLink, realtimeGeneration
20372
21918
  realtimeSessionId: null,
20373
21919
  coordinatorCall: null,
20374
21920
  workhorseLink: cloneAndFreeze$3(workhorseLink),
20375
- realtimeGeneration: realtimeGeneration === null ? null : freeze$2({ ...realtimeGeneration })
21921
+ realtimeGeneration: realtimeGeneration === null ? null : freeze$1({ ...realtimeGeneration })
20376
21922
  })
20377
21923
  });
20378
21924
  }
@@ -20468,7 +22014,7 @@ const CALLBACK_BUFFER_LIMIT = 64;
20468
22014
  * @param value - The value to freeze.
20469
22015
  * @returns The same value, frozen.
20470
22016
  */
20471
- function freeze$1(value) {
22017
+ function freeze(value) {
20472
22018
  return Object.freeze(value);
20473
22019
  }
20474
22020
  /**
@@ -20741,7 +22287,7 @@ function createCodexCoordinatorCallbacks(options) {
20741
22287
  news: workhorseNews.message,
20742
22288
  enqueue
20743
22289
  });
20744
- return freeze$1({
22290
+ return freeze({
20745
22291
  enqueue,
20746
22292
  /**
20747
22293
  * Queue the workhorse news a Codex notification carries, if any.
@@ -20804,131 +22350,6 @@ function createCodexCoordinatorCallbacks(options) {
20804
22350
  }
20805
22351
  });
20806
22352
  }
20807
- // src/runtime/voice/coordinator/tools-and-work/tool-contract/protocol/tool-inputs.ts
20808
- /**
20809
- * The checkout whose workhorse a tool works with: the directory the host names it by.
20810
- */
20811
- const CheckoutSchema = z.string().min(1).max(4096);
20812
- const InspectWorkhorseInputSchema = z.object({ checkout: CheckoutSchema }).strict();
20813
- const DelegateToWorkhorseInputSchema = z.object({
20814
- checkout: CheckoutSchema,
20815
- input: z.string().min(1).max(4096),
20816
- transcriptDelta: z.string().min(0).max(4096)
20817
- }).strict();
20818
- const QueueOperationSchema = z.enum([
20819
- "list",
20820
- "add",
20821
- "update",
20822
- "delete",
20823
- "reorder",
20824
- "start"
20825
- ]);
20826
- const QueueSubmissionIdSchema = z.string().min(1).max(128);
20827
- const QueuePromptSchema = z.string().min(1).max(16384);
20828
- const QueueOrderSchema = z.array(QueueSubmissionIdSchema).min(1).max(100).refine((values) => new Set(values).size === values.length, "submission ids must be unique");
20829
- const QueueListInputSchema = z.object({
20830
- checkout: CheckoutSchema,
20831
- operation: z.literal("list")
20832
- }).strict();
20833
- const QueueAddInputSchema = z.object({
20834
- checkout: CheckoutSchema,
20835
- operation: z.literal("add"),
20836
- prompt: QueuePromptSchema
20837
- }).strict();
20838
- const QueueUpdateInputSchema = z.object({
20839
- checkout: CheckoutSchema,
20840
- operation: z.literal("update"),
20841
- submissionId: QueueSubmissionIdSchema,
20842
- prompt: QueuePromptSchema
20843
- }).strict();
20844
- const QueueDeleteInputSchema = z.object({
20845
- checkout: CheckoutSchema,
20846
- operation: z.literal("delete"),
20847
- submissionId: QueueSubmissionIdSchema
20848
- }).strict();
20849
- const QueueReorderInputSchema = z.object({
20850
- checkout: CheckoutSchema,
20851
- operation: z.literal("reorder"),
20852
- orderedSubmissionIds: QueueOrderSchema
20853
- }).strict();
20854
- const QueueStartInputSchema = z.object({
20855
- checkout: CheckoutSchema,
20856
- operation: z.literal("start"),
20857
- submissionId: QueueSubmissionIdSchema
20858
- }).strict();
20859
- const ManageWorkhorseQueueInputSchema = z.discriminatedUnion("operation", [
20860
- QueueListInputSchema,
20861
- QueueAddInputSchema,
20862
- QueueUpdateInputSchema,
20863
- QueueDeleteInputSchema,
20864
- QueueReorderInputSchema,
20865
- QueueStartInputSchema
20866
- ]);
20867
- const SteerWorkhorseInputSchema = z.object({
20868
- checkout: CheckoutSchema,
20869
- input: z.string().min(1).max(4096)
20870
- }).strict();
20871
- /** A stop names no workhorse: it stops every running workhorse of the calling tab session. */
20872
- const StopWorkhorsesInputSchema = z.object({}).strict();
20873
- const ResolveSpokenApprovalInputSchema = z.object({ verdict: z.enum(["accept", "decline"]) }).strict();
20874
- const WORKHORSE_TOOL_INPUT_SCHEMAS = Object.freeze({
20875
- inspect_workhorse: InspectWorkhorseInputSchema,
20876
- delegate_to_workhorse: DelegateToWorkhorseInputSchema,
20877
- manage_workhorse_queue: ManageWorkhorseQueueInputSchema,
20878
- steer_workhorse: SteerWorkhorseInputSchema,
20879
- stop_workhorses: StopWorkhorsesInputSchema
20880
- });
20881
- const VOICE_TOOL_INPUT_SCHEMAS = Object.freeze({ resolve_spoken_approval: ResolveSpokenApprovalInputSchema });
20882
- /**
20883
- * Validates the arguments the coordinator passed to one workhorse tool.
20884
- * @param toolName - The workhorse tool being called.
20885
- * @param input - The raw tool arguments.
20886
- * @returns The validated arguments.
20887
- */
20888
- function parseWorkhorseToolInput(toolName, input) {
20889
- return WORKHORSE_TOOL_INPUT_SCHEMAS[toolName].parse(input);
20890
- }
20891
- /**
20892
- * Validates the arguments the coordinator passed to one voice tool.
20893
- * @param toolName - The voice tool being called.
20894
- * @param input - The raw tool arguments.
20895
- * @returns The validated arguments.
20896
- */
20897
- function parseVoiceToolInput(toolName, input) {
20898
- return VOICE_TOOL_INPUT_SCHEMAS[toolName].parse(input);
20899
- }
20900
- /**
20901
- * Narrows a tool name to the workhorse namespace.
20902
- * @param toolName - Any coordinator tool name.
20903
- * @returns Whether the workhorse namespace declares the tool.
20904
- */
20905
- function isWorkhorseToolName(toolName) {
20906
- return WORKHORSE_TOOL_NAMES.some((candidate) => candidate === toolName);
20907
- }
20908
- /**
20909
- * Narrows a tool name to the voice namespace.
20910
- * @param toolName - Any coordinator tool name.
20911
- * @returns Whether the voice namespace declares the tool.
20912
- */
20913
- function isVoiceToolName(toolName) {
20914
- return VOICE_TOOL_NAMES.some((candidate) => candidate === toolName);
20915
- }
20916
- /**
20917
- * Validates tool arguments against the schema of the namespace the call arrived in, refusing
20918
- * a tool name the namespace does not declare even when another namespace does.
20919
- * @param role - The role of the namespace the call was made through.
20920
- * @param toolName - The tool being called.
20921
- * @param input - The raw tool arguments.
20922
- * @returns The validated arguments.
20923
- */
20924
- function parseCoordinatorToolInput(role, toolName, input) {
20925
- if (role === "workhorse") {
20926
- if (!isWorkhorseToolName(toolName)) throw new TypeError(`The ${role} namespace does not declare ${toolName}.`);
20927
- return parseWorkhorseToolInput(toolName, input);
20928
- }
20929
- if (!isVoiceToolName(toolName)) throw new TypeError(`The ${role} namespace does not declare ${toolName}.`);
20930
- return parseVoiceToolInput(toolName, input);
20931
- }
20932
22353
  // src/runtime/voice/coordinator/tools-and-work/coordinator-tools/rules/call-identity.ts
20933
22354
  var CoordinatorToolValidationError = class extends Error {
20934
22355
  name = "CoordinatorToolValidationError";
@@ -20969,7 +22390,7 @@ const LOGICAL_CALL_FIELDS = [
20969
22390
  * @param right - The other correlation.
20970
22391
  * @returns Whether every field matches.
20971
22392
  */
20972
- function sameCall$1(left, right) {
22393
+ function sameCall(left, right) {
20973
22394
  return LOGICAL_CALL_FIELDS.every((field) => left[field] === right[field]);
20974
22395
  }
20975
22396
  const IDENTITY_REFUSALS = Object.freeze({
@@ -21103,7 +22524,7 @@ function assertLogicalCall(options, request) {
21103
22524
  assertCallIdentitiesMatchParams(options, call, request);
21104
22525
  assertReviewedManifest(options.tools, call);
21105
22526
  const current = options.authority.currentCall();
21106
- if (current === null || !sameCall$1(current, call)) fail("invalid_call", "The coordinator call is no longer the current executing call.");
22527
+ if (current === null || !sameCall(current, call)) fail("invalid_call", "The coordinator call is no longer the current executing call.");
21107
22528
  return call;
21108
22529
  }
21109
22530
  // src/runtime/voice/coordinator/tools-and-work/coordinator-tools/rules/call-provenance.ts
@@ -21179,37 +22600,6 @@ function workhorseBinding(options, call, coordinator, target) {
21179
22600
  assertOwnedWorkhorse(binding);
21180
22601
  return binding;
21181
22602
  }
21182
- // src/runtime/workhorses/workhorse-operations/protocol/contract.ts
21183
- Object.freeze([
21184
- "inspect_workhorse",
21185
- "delegate_to_workhorse",
21186
- "manage_workhorse_queue",
21187
- "steer_workhorse"
21188
- ]);
21189
- var CodexWorkhorseOperationsError = class extends Error {
21190
- name = "CodexWorkhorseOperationsError";
21191
- code;
21192
- operation;
21193
- outcome;
21194
- operationId;
21195
- cause;
21196
- /**
21197
- * Build the error, defaulting every optional fact to null so a caller can always ask what the
21198
- * failure proved about delivery without checking whether the field exists.
21199
- * @param code - Why the operation could not proceed.
21200
- * @param message - The diagnostic for the caller.
21201
- * @param options - The operation, settled outcome, operation identity and underlying cause,
21202
- * as far as they are known at the point of failure.
21203
- */
21204
- constructor(code, message, options = {}) {
21205
- super(message);
21206
- this.code = code;
21207
- this.operation = options.operation ?? null;
21208
- this.outcome = options.outcome ?? null;
21209
- this.operationId = options.operationId ?? null;
21210
- this.cause = options.cause;
21211
- }
21212
- };
21213
22603
  // src/runtime/voice/coordinator/tools-and-work/coordinator-tools/rules/validation.ts
21214
22604
  /** The reviewed namespace role and tool name pair a logical call may carry. */
21215
22605
  const DeclaredToolSchema = z.union([z.object({
@@ -21360,43 +22750,18 @@ function declaredTool(options, call) {
21360
22750
  return declared.data;
21361
22751
  }
21362
22752
  /**
21363
- * Resolve the active workhorse turn a steer must target; the server proves it, never the caller.
21364
- * @param options - The dispatcher options carrying the server authority.
21365
- * @returns The expected turn id.
21366
- */
21367
- function steerExpectedTurnId(options) {
21368
- const expectedTurnId = options.authority.expectedTurnId();
21369
- if (expectedTurnId === null) fail("busy", "The server has not proven an active workhorse turn.");
21370
- try {
21371
- options.identity.decoder.parseTurnId(expectedTurnId);
21372
- } catch (error) {
21373
- throw mapIdentityFailure(error);
21374
- }
21375
- return expectedTurnId;
21376
- }
21377
- /**
21378
22753
  * Assemble a validated workhorse-namespace call for one parsed input.
21379
- * @param options - The dispatcher options carrying the server authority.
21380
22754
  * @param evidence - The call, fingerprint and coordinator facts.
21381
22755
  * @param parsed - The tagged workhorse tool input.
21382
22756
  * @param binding - The current workhorse binding.
21383
22757
  * @returns The validated call.
21384
22758
  */
21385
- function workhorseCall(options, evidence, parsed, binding) {
21386
- const role = "workhorse";
21387
- if (parsed.tool === "steer_workhorse") return Object.freeze({
21388
- ...evidence,
21389
- role,
21390
- ...parsed,
21391
- workhorseBinding: binding,
21392
- expectedTurnId: steerExpectedTurnId(options)
21393
- });
22759
+ function workhorseCall(evidence, parsed, binding) {
21394
22760
  return Object.freeze({
21395
22761
  ...evidence,
21396
- role,
22762
+ role: "workhorse",
21397
22763
  ...parsed,
21398
- workhorseBinding: binding,
21399
- expectedTurnId: null
22764
+ workhorseBinding: binding
21400
22765
  });
21401
22766
  }
21402
22767
  /**
@@ -21421,17 +22786,15 @@ function validateCoordinatorToolRequest(options, request) {
21421
22786
  ...evidence,
21422
22787
  role: "voice",
21423
22788
  ...parsed,
21424
- workhorseBinding: null,
21425
- expectedTurnId: null
22789
+ workhorseBinding: null
21426
22790
  });
21427
22791
  if (parsed.tool === "stop_workhorses") return Object.freeze({
21428
22792
  ...evidence,
21429
22793
  role: "workhorse",
21430
22794
  ...parsed,
21431
- workhorseBinding: null,
21432
- expectedTurnId: null
22795
+ workhorseBinding: null
21433
22796
  });
21434
- return workhorseCall(options, evidence, parsed, workhorseBinding(options, call, coordinator, {
22797
+ return workhorseCall(evidence, parsed, workhorseBinding(options, call, coordinator, {
21435
22798
  checkout: parsed.input.checkout,
21436
22799
  delegation: parsed.tool === "delegate_to_workhorse"
21437
22800
  }));
@@ -21460,254 +22823,6 @@ function callKey(request) {
21460
22823
  function logicalCallKey(call) {
21461
22824
  return logicalToolCallKey(call);
21462
22825
  }
21463
- // src/runtime/voice/coordinator/tools-and-work/tool-contract/protocol/dynamic-tool-envelopes.ts
21464
- const DYNAMIC_TOOL_REFUSAL_REASONS = Object.freeze([
21465
- "invalid_call",
21466
- "not_ready",
21467
- "not_loaded",
21468
- "not_controllable",
21469
- "system_error",
21470
- "stale_child",
21471
- "prior_epoch",
21472
- "unknown_provenance",
21473
- "approval_declined",
21474
- "cycle",
21475
- "busy",
21476
- "expired",
21477
- "unsupported"
21478
- ]);
21479
- const DynamicToolRefusalReasonSchema = z.enum(DYNAMIC_TOOL_REFUSAL_REASONS);
21480
- const OpaqueIdSchema = z.string().min(1).max(128);
21481
- const BoundedDiagnosticSchema = z.string().min(1).max(4096);
21482
- const JsonObjectSchema = z.record(z.string(), z.json());
21483
- const DynamicToolOkEnvelopeSchema = z.object({
21484
- tag: z.literal("ok"),
21485
- operationId: OpaqueIdSchema,
21486
- value: JsonObjectSchema
21487
- }).strict();
21488
- const DynamicToolRefusedEnvelopeSchema = z.object({
21489
- tag: z.literal("refused"),
21490
- reason: DynamicToolRefusalReasonSchema,
21491
- message: BoundedDiagnosticSchema
21492
- }).strict();
21493
- const DynamicToolApprovalRequiredEnvelopeSchema = z.object({
21494
- tag: z.literal("approval_required"),
21495
- operationId: OpaqueIdSchema,
21496
- summary: BoundedDiagnosticSchema
21497
- }).strict();
21498
- const DYNAMIC_TOOL_OUTCOME_UNKNOWN_MESSAGE = "The request may have taken effect. Inspect authoritative state before another mutation.";
21499
- const DynamicToolOutcomeUnknownEnvelopeSchema = z.object({
21500
- tag: z.literal("outcome_unknown"),
21501
- operationId: OpaqueIdSchema,
21502
- message: z.literal(DYNAMIC_TOOL_OUTCOME_UNKNOWN_MESSAGE)
21503
- }).strict();
21504
- const DynamicToolEnvelopeSchema = z.discriminatedUnion("tag", [
21505
- DynamicToolOkEnvelopeSchema,
21506
- DynamicToolRefusedEnvelopeSchema,
21507
- DynamicToolApprovalRequiredEnvelopeSchema,
21508
- DynamicToolOutcomeUnknownEnvelopeSchema
21509
- ]);
21510
- const DynamicToolEnvelopeTextSchema = z.string().min(1).max(16384).superRefine((text, context) => {
21511
- let value;
21512
- try {
21513
- value = JSON.parse(text);
21514
- } catch {
21515
- context.addIssue({
21516
- code: "custom",
21517
- message: "tool response text must be JSON"
21518
- });
21519
- return;
21520
- }
21521
- const parsed = DynamicToolEnvelopeSchema.safeParse(value);
21522
- if (!parsed.success || JSON.stringify(parsed.data) !== text) context.addIssue({
21523
- code: "custom",
21524
- message: "tool response text must be canonical JSON"
21525
- });
21526
- });
21527
- const DynamicToolContentItemsSchema = z.tuple([z.object({
21528
- type: z.literal("inputText"),
21529
- text: DynamicToolEnvelopeTextSchema
21530
- }).strict()]);
21531
- /** Responses for calls that passed the coordinator's identity/manifest checks. */
21532
- const ValidDynamicToolResponseSchema = z.object({
21533
- contentItems: DynamicToolContentItemsSchema,
21534
- success: z.literal(true)
21535
- }).strict();
21536
- /**
21537
- * Reads the envelope tag out of response text without trusting it to be an envelope.
21538
- * @param text - The tool response text.
21539
- * @returns The tag when the text is a valid envelope, otherwise undefined.
21540
- */
21541
- function envelopeTag(text) {
21542
- let value;
21543
- try {
21544
- value = JSON.parse(text);
21545
- } catch {
21546
- return;
21547
- }
21548
- const parsed = DynamicToolEnvelopeSchema.safeParse(value);
21549
- return parsed.success ? parsed.data.tag : void 0;
21550
- }
21551
- /** Responses for calls rejected before a tool call could be established. */
21552
- const UnknownDynamicToolResponseSchema = z.object({
21553
- contentItems: DynamicToolContentItemsSchema,
21554
- success: z.literal(false)
21555
- }).strict().superRefine((response, context) => {
21556
- if (envelopeTag(response.contentItems[0].text) !== "refused") context.addIssue({
21557
- code: "custom",
21558
- path: ["contentItems"],
21559
- message: "unknown calls must return a refused envelope"
21560
- });
21561
- });
21562
- // src/runtime/voice/coordinator/tools-and-work/tool-contract/protocol/tool-results.ts
21563
- const DeliverySchema = z.enum([
21564
- "delivered",
21565
- "not_delivered",
21566
- "outcome_unknown"
21567
- ]);
21568
- const NullableOpaqueIdSchema = OpaqueIdSchema.nullable();
21569
- const QueuedSubmissionIdsSchema = z.array(QueueSubmissionIdSchema).max(100);
21570
- const InspectWorkhorseResultSchema = z.object({
21571
- threadId: OpaqueIdSchema,
21572
- status: CodexThreadStatusTypeSchema,
21573
- activeTurnId: NullableOpaqueIdSchema,
21574
- queuedSubmissionIds: QueuedSubmissionIdsSchema
21575
- }).strict();
21576
- const DelegateToWorkhorseResultSchema = z.object({
21577
- mode: z.enum(["started", "queued"]),
21578
- clientUserMessageId: OpaqueIdSchema,
21579
- queuedSubmissionId: NullableOpaqueIdSchema,
21580
- turnId: NullableOpaqueIdSchema
21581
- }).strict();
21582
- const ManageWorkhorseQueueResultSchema = z.object({
21583
- operation: QueueOperationSchema,
21584
- queuedSubmissionIds: QueuedSubmissionIdsSchema
21585
- }).strict();
21586
- const SteerWorkhorseResultSchema = z.object({
21587
- turnId: OpaqueIdSchema,
21588
- delivery: DeliverySchema
21589
- }).strict();
21590
- const STOP_OUTCOMES = ["interrupt_sent", "idle"];
21591
- const StopWorkhorsesResultSchema = z.object({ stopped: z.array(z.object({
21592
- checkout: z.string().min(1).max(4096),
21593
- outcome: z.enum(STOP_OUTCOMES)
21594
- }).strict()).max(100) }).strict();
21595
- const ResolveSpokenApprovalResultSchema = z.object({
21596
- verdict: z.enum(["accept", "decline"]),
21597
- settlement: DeliverySchema
21598
- }).strict();
21599
- const COORDINATOR_TOOL_RESULT_SCHEMAS = Object.freeze({
21600
- inspect_workhorse: InspectWorkhorseResultSchema,
21601
- delegate_to_workhorse: DelegateToWorkhorseResultSchema,
21602
- manage_workhorse_queue: ManageWorkhorseQueueResultSchema,
21603
- steer_workhorse: SteerWorkhorseResultSchema,
21604
- stop_workhorses: StopWorkhorsesResultSchema,
21605
- resolve_spoken_approval: ResolveSpokenApprovalResultSchema
21606
- });
21607
- /**
21608
- * Validates the value a server produced for one coordinator tool before it is returned to the
21609
- * model, so a malformed server result is refused rather than echoed as a success.
21610
- * @param toolName - The tool whose result is being checked.
21611
- * @param value - The raw server result.
21612
- * @returns The validated result value.
21613
- */
21614
- function parseCoordinatorToolResult(toolName, value) {
21615
- return COORDINATOR_TOOL_RESULT_SCHEMAS[toolName].parse(value);
21616
- }
21617
- const JsonStringSchema = Object.freeze({ type: "string" });
21618
- const JsonNullableStringSchema = deepFreeze$5({ anyOf: [JsonStringSchema, Object.freeze({ type: "null" })] });
21619
- /**
21620
- * Builds the closed JSON Schema object that mirrors one zod result schema for the manifest.
21621
- * @param properties - The JSON Schema of each result field.
21622
- * @param required - The fields every result must carry.
21623
- * @returns A frozen JSON Schema object that rejects unknown fields.
21624
- */
21625
- function strictResultObject(properties, required) {
21626
- return deepFreeze$5({
21627
- type: "object",
21628
- properties,
21629
- required: [...required],
21630
- additionalProperties: false
21631
- });
21632
- }
21633
- const ResultOperationSchema = deepFreeze$5({
21634
- type: "string",
21635
- enum: [...QueueOperationSchema.options]
21636
- });
21637
- const ResultStatusSchema = deepFreeze$5({
21638
- type: "string",
21639
- enum: [...CODEX_THREAD_STATUS_TYPES]
21640
- });
21641
- const ResultDeliverySchema = deepFreeze$5({
21642
- type: "string",
21643
- enum: [
21644
- "delivered",
21645
- "not_delivered",
21646
- "outcome_unknown"
21647
- ]
21648
- });
21649
- const ResultQueuedSubmissionIdsSchema = deepFreeze$5({
21650
- type: "array",
21651
- items: JsonStringSchema,
21652
- maxItems: 100
21653
- });
21654
- const TOOL_SUCCESS_RESULT_SCHEMAS = deepFreeze$5({
21655
- inspect_workhorse: strictResultObject({
21656
- threadId: JsonStringSchema,
21657
- status: ResultStatusSchema,
21658
- activeTurnId: JsonNullableStringSchema,
21659
- queuedSubmissionIds: ResultQueuedSubmissionIdsSchema
21660
- }, [
21661
- "threadId",
21662
- "status",
21663
- "activeTurnId",
21664
- "queuedSubmissionIds"
21665
- ]),
21666
- delegate_to_workhorse: strictResultObject({
21667
- mode: deepFreeze$5({
21668
- type: "string",
21669
- enum: ["started", "queued"]
21670
- }),
21671
- clientUserMessageId: JsonStringSchema,
21672
- queuedSubmissionId: JsonNullableStringSchema,
21673
- turnId: JsonNullableStringSchema
21674
- }, [
21675
- "mode",
21676
- "clientUserMessageId",
21677
- "queuedSubmissionId",
21678
- "turnId"
21679
- ]),
21680
- manage_workhorse_queue: strictResultObject({
21681
- operation: ResultOperationSchema,
21682
- queuedSubmissionIds: ResultQueuedSubmissionIdsSchema
21683
- }, ["operation", "queuedSubmissionIds"]),
21684
- steer_workhorse: strictResultObject({
21685
- turnId: JsonStringSchema,
21686
- delivery: ResultDeliverySchema
21687
- }, ["turnId", "delivery"]),
21688
- stop_workhorses: strictResultObject({ stopped: deepFreeze$5({
21689
- type: "array",
21690
- maxItems: 100,
21691
- items: strictResultObject({
21692
- checkout: deepFreeze$5({
21693
- type: "string",
21694
- minLength: 1,
21695
- maxLength: 4096
21696
- }),
21697
- outcome: deepFreeze$5({
21698
- type: "string",
21699
- enum: [...STOP_OUTCOMES]
21700
- })
21701
- }, ["checkout", "outcome"])
21702
- }) }, ["stopped"]),
21703
- resolve_spoken_approval: strictResultObject({
21704
- verdict: deepFreeze$5({
21705
- type: "string",
21706
- enum: ["accept", "decline"]
21707
- }),
21708
- settlement: ResultDeliverySchema
21709
- }, ["verdict", "settlement"])
21710
- });
21711
22826
  // src/runtime/voice/coordinator/tools-and-work/coordinator-tools/rules/response.ts
21712
22827
  /**
21713
22828
  * The reviewed result shapes without their strictness: parsing through these keeps exactly the
@@ -21936,15 +23051,21 @@ function queueRequest(call, input, operation) {
21936
23051
  };
21937
23052
  }
21938
23053
  /**
21939
- * Start the stop of every workhorse of the tab session, with each outcome named as the tool
21940
- * reports it.
23054
+ * Start the stop of every workhorse's work tree in the tab session. A stop that did not show all
23055
+ * work ended names the tools that recover: look again, or stop again.
21941
23056
  * @param options - The dispatcher options, which stop the tab session's workhorses.
23057
+ * @param call - The coordinator call that asked for the stop.
21942
23058
  * @returns The pending stops.
21943
23059
  */
21944
- function invokeStop(options) {
21945
- return options.stopWork().then((stops) => ({ stopped: stops.map(({ checkout, outcome }) => ({
23060
+ function invokeStop(options, call) {
23061
+ return options.stopWork(call.turnId).then((stops) => ({ stopped: stops.map(({ checkout, outcome, remaining }) => ({
21946
23062
  checkout,
21947
- outcome: outcome === "interrupted" ? "interrupt_sent" : outcome
23063
+ outcome,
23064
+ remaining: remaining.map(({ threadId, state }) => ({
23065
+ threadId,
23066
+ state
23067
+ })),
23068
+ recovery: outcome === "partial" || outcome === "unconfirmed" ? ["inspect_workhorse", "stop_workhorses"] : []
21948
23069
  })) }));
21949
23070
  }
21950
23071
  /**
@@ -21960,11 +23081,12 @@ function invokeStop(options) {
21960
23081
  function invokeCheckoutWorkhorse(options, validated, operation) {
21961
23082
  const { call } = validated;
21962
23083
  const { checkout } = validated.input;
21963
- const operations = options.workhorseFor(checkout)?.operations;
21964
- if (operations === void 0) return Promise.reject(Object.assign(/* @__PURE__ */ new Error(`This conversation has no workhorse in ${checkout}.`), {
23084
+ const workhorse = options.workhorseFor(checkout);
23085
+ if (workhorse === null) return Promise.reject(Object.assign(/* @__PURE__ */ new Error(`This conversation has no workhorse in ${checkout}.`), {
21965
23086
  code: "not_ready",
21966
23087
  outcome: "not_delivered"
21967
23088
  }));
23089
+ const { operations } = workhorse;
21968
23090
  if (validated.tool === "inspect_workhorse") return operations.inspect({ call });
21969
23091
  if (validated.tool === "delegate_to_workhorse") {
21970
23092
  const { input, transcriptDelta } = validated.input;
@@ -21978,7 +23100,6 @@ function invokeCheckoutWorkhorse(options, validated, operation) {
21978
23100
  if (validated.tool === "manage_workhorse_queue") return operations.manageQueue(queueRequest(call, validated.input, operation));
21979
23101
  return operations.steer({
21980
23102
  call,
21981
- expectedTurnId: validated.expectedTurnId,
21982
23103
  input: validated.input.input,
21983
23104
  operationId: operation.id
21984
23105
  });
@@ -21992,22 +23113,38 @@ function invokeCheckoutWorkhorse(options, validated, operation) {
21992
23113
  * @returns The pending result.
21993
23114
  */
21994
23115
  function invokeWorkhorse(options, validated, operation) {
21995
- return validated.tool === "stop_workhorses" ? invokeStop(options) : invokeCheckoutWorkhorse(options, validated, operation);
23116
+ return validated.tool === "stop_workhorses" ? invokeStop(options, validated.call) : invokeCheckoutWorkhorse(options, validated, operation);
21996
23117
  }
21997
23118
  /**
21998
23119
  * Build the successful response for a workhorse port result under its still-current operation.
21999
23120
  * The result is narrowed by the tool's reviewed result schema rather than by a static pairing of
22000
- * tool name and port type.
23121
+ * tool name and port type. An inspection also says where the workhorse's last stop stands, which
23122
+ * the tab session knows and the workhorse operations do not.
22001
23123
  * @param options - The dispatcher options carrying the operation authority.
22002
- * @param tool - The tool that produced the result.
23124
+ * @param validated - The call that produced the result.
22003
23125
  * @param operation - The issued operation identity the effect ran under.
22004
23126
  * @param result - The result as the port produced it.
22005
23127
  * @returns The frozen response.
22006
23128
  */
22007
- function workhorseResponse(options, tool, operation, result) {
23129
+ function workhorseResponse(options, validated, operation, result) {
22008
23130
  const current = operationIdentity(options, operation.id);
22009
23131
  if (current.id !== operation.id) throw new TypeError("The workhorse operation identity changed.");
22010
- return okPortResponse(tool, current.wire, result);
23132
+ return okPortResponse(validated.tool, current.wire, withLastStop(options, validated, result));
23133
+ }
23134
+ /**
23135
+ * An inspection's answer with where the workhorse's last stop stands, which only this server
23136
+ * knows; any other answer as it is.
23137
+ * @param options - The dispatcher options that find the workhorse.
23138
+ * @param validated - The validated call.
23139
+ * @param result - The port's answer.
23140
+ * @returns The answer the coordinator hears.
23141
+ */
23142
+ function withLastStop(options, validated, result) {
23143
+ if (validated.tool !== "inspect_workhorse" || typeof result !== "object" || result === null) return result;
23144
+ return {
23145
+ ...result,
23146
+ lastStop: options.workhorseFor(validated.input.checkout)?.lastStop() ?? null
23147
+ };
22011
23148
  }
22012
23149
  /**
22013
23150
  * Whether a thrown error belongs to this call's operation; an error naming no operation is taken
@@ -22165,7 +23302,7 @@ function workhorseResult(context, state, validated, operation, result) {
22165
23302
  if (isMutation(validated)) return complete(outcomeUnknownResponse(operation.wire), true);
22166
23303
  return complete(refusedResponse(error instanceof CoordinatorToolValidationError ? error.reason : "unknown_provenance", errorMessage$3(error)), true);
22167
23304
  }
22168
- return complete(workhorseResponse(context.options, validated.tool, operation, result), true);
23305
+ return complete(workhorseResponse(context.options, validated, operation, result), true);
22169
23306
  }
22170
23307
  /**
22171
23308
  * Plan one validated call: a voice call runs as it is, a workhorse call runs under a freshly
@@ -24530,7 +25667,7 @@ function recordKey(record) {
24530
25667
  * @param right - The other binding.
24531
25668
  * @returns True when every field matches.
24532
25669
  */
24533
- function sameBinding$3(left, right) {
25670
+ function sameBinding$2(left, right) {
24534
25671
  return left.child === right.child && left.epoch === right.epoch && left.link === right.link && left.target === right.target && left.effect === right.effect;
24535
25672
  }
24536
25673
  /**
@@ -24549,7 +25686,7 @@ function sameSpokenEffectPresentation(presentation, approval) {
24549
25686
  presentation.turnId === approval.turnId,
24550
25687
  presentation.itemId === approval.itemId,
24551
25688
  presentation.approvalId === approval.approvalId,
24552
- sameBinding$3(presentation.binding, approval.binding)
25689
+ sameBinding$2(presentation.binding, approval.binding)
24553
25690
  ].every((matched) => matched);
24554
25691
  }
24555
25692
  /**
@@ -25200,7 +26337,7 @@ function isUnchangedApproval(context, slot) {
25200
26337
  return [
25201
26338
  approval.state === "pending",
25202
26339
  approval.approvalId === slot.approvalId,
25203
- sameBinding$3(approval.binding, slot.approvalBinding),
26340
+ sameBinding$2(approval.binding, slot.approvalBinding),
25204
26341
  eligibility.eligible
25205
26342
  ].every((matched) => matched);
25206
26343
  }
@@ -25579,7 +26716,7 @@ function sameArmedApproval(approval, slot) {
25579
26716
  approval.approvalId === slot.approvalId,
25580
26717
  approval.family === slot.approvalFamily,
25581
26718
  approval.expiresAtMs === slot.approvalExpiresAtMs,
25582
- sameBinding$3(approval.binding, slot.approvalBinding)
26719
+ sameBinding$2(approval.binding, slot.approvalBinding)
25583
26720
  ].every((matched) => matched);
25584
26721
  }
25585
26722
  /**
@@ -27024,7 +28161,7 @@ function freezeBinding(binding) {
27024
28161
  * @param right - The other target.
27025
28162
  * @returns True when all four identities agree.
27026
28163
  */
27027
- function sameTarget$1(left, right) {
28164
+ function sameTarget(left, right) {
27028
28165
  return left.threadId === right.threadId && left.childId === right.childId && left.epoch === right.epoch && left.operationId === right.operationId;
27029
28166
  }
27030
28167
  /**
@@ -27034,9 +28171,9 @@ function sameTarget$1(left, right) {
27034
28171
  * @param right - The proposed binding, if any.
27035
28172
  * @returns True when both are absent or both carry the same authority.
27036
28173
  */
27037
- function sameBinding$2(left, right) {
28174
+ function sameBinding$1(left, right) {
27038
28175
  if (left === null || right === null) return left === right;
27039
- return left.linkKey === right.linkKey && sameTarget$1(left.target, right.target) && sameLink$1(left.link, right.link);
28176
+ return left.linkKey === right.linkKey && sameTarget(left.target, right.target) && sameLink$1(left.link, right.link);
27040
28177
  }
27041
28178
  /**
27042
28179
  * The outcome for a change seen while no binding was active.
@@ -27197,7 +28334,7 @@ function createCodexThreadContextController(options) {
27197
28334
  const assertTransitionAllowed = (expected, next) => {
27198
28335
  if (disposed) throw new CodexThreadContextControllerError("disposed", "The thread-context controller is disposed.");
27199
28336
  if (!Number.isSafeInteger(expected.revision) || expected.revision !== revision) throw new CodexThreadContextControllerError("stale_binding", `Thread-context binding revision ${expected.revision} is stale; current revision is ${revision}.`);
27200
- if (sameBinding$2(snapshot().binding, next)) throw new CodexThreadContextControllerError("duplicate_binding", "The thread-context binding transition does not change authority.");
28337
+ if (sameBinding$1(snapshot().binding, next)) throw new CodexThreadContextControllerError("duplicate_binding", "The thread-context binding transition does not change authority.");
27201
28338
  };
27202
28339
  /**
27203
28340
  * Creates the delivery port for a newly activated binding; its child
@@ -27380,345 +28517,6 @@ function settleDurable(options, state, requested, detail) {
27380
28517
  state.durableSettled = true;
27381
28518
  return outcome;
27382
28519
  }
27383
- Object.freeze([
27384
- "list",
27385
- "add",
27386
- "update",
27387
- "delete",
27388
- "reorder",
27389
- "start"
27390
- ]);
27391
- var CodexWorkhorseQueueError = class extends Error {
27392
- name = "CodexWorkhorseQueueError";
27393
- code;
27394
- operation;
27395
- outcome;
27396
- queue;
27397
- cause;
27398
- /**
27399
- * Build the error, defaulting every optional fact to null so a caller can always ask what the
27400
- * failure proved about delivery and about the queue without checking whether the field exists.
27401
- * @param code - Why the queue refused.
27402
- * @param message - The diagnostic for the caller.
27403
- * @param options - The operation, settled outcome, queue snapshot and underlying cause, as far
27404
- * as they are known at the point of failure.
27405
- */
27406
- constructor(code, message, options = {}) {
27407
- super(message);
27408
- this.code = code;
27409
- this.operation = options.operation ?? null;
27410
- this.outcome = options.outcome ?? null;
27411
- this.queue = options.queue ?? null;
27412
- this.cause = options.cause;
27413
- }
27414
- };
27415
- // src/runtime/workhorses/workhorse-operations/rules/operation-errors.ts
27416
- /**
27417
- * Thread-link refusal reasons that map to a specific operation error code; every other reason
27418
- * means the link is simply not ready.
27419
- */
27420
- const LINK_REASON_CODES = Object.freeze({
27421
- stale_child: "stale_child",
27422
- prior_epoch: "prior_epoch",
27423
- thread_status_not_loaded: "not_loaded",
27424
- thread_status_system_error: "system_error",
27425
- direct_input_false: "not_controllable",
27426
- direct_input_unknown: "not_controllable",
27427
- thread_start_outcome_unknown: "unknown_provenance",
27428
- unknown_provenance: "unknown_provenance",
27429
- thread_list_missing: "unknown_provenance",
27430
- thread_list_ambiguous: "unknown_provenance",
27431
- thread_loaded_list_ambiguous: "unknown_provenance",
27432
- thread_source_custom: "unknown_provenance",
27433
- thread_source_subagent: "unknown_provenance",
27434
- thread_source_unknown: "unknown_provenance",
27435
- thread_loaded_list_missing: "unknown_provenance"
27436
- });
27437
- /** Queue error codes that leave the remote effect's outcome undecidable once it has started. */
27438
- const UNDECIDABLE_QUEUE_CODES = /* @__PURE__ */ new Set(["reconciliation_failed", "stale_link"]);
27439
- /**
27440
- * Build an operations error; the one constructor call site keeps the option shape in one place.
27441
- * @param code - The error code the caller can act on.
27442
- * @param message - The human-readable reason.
27443
- * @param options - Operation, outcome, identity and cause metadata.
27444
- * @returns The error, not yet thrown.
27445
- */
27446
- function operationError(code, message, options = {}) {
27447
- return new CodexWorkhorseOperationsError(code, message, options);
27448
- }
27449
- /**
27450
- * Read a message from any thrown value for event detail and error chaining.
27451
- * @param error - The thrown value.
27452
- * @returns Its message, or a placeholder for non-Error throws.
27453
- */
27454
- function messageOf(error) {
27455
- return error instanceof Error ? error.message : "unknown error";
27456
- }
27457
- /**
27458
- * Translate a thread-link refusal reason into the operation error code callers act on.
27459
- * @param reason - The classifier's reason string.
27460
- * @returns The matching operation error code, `not_ready` for unmapped reasons.
27461
- */
27462
- function mapLinkReason(reason) {
27463
- return LINK_REASON_CODES[reason] ?? "not_ready";
27464
- }
27465
- /**
27466
- * Decide what a failed session mutation proved about delivery.
27467
- * @param error - The thrown value from the session port.
27468
- * @returns The outcome the session asserted, or unknown when it asserted nothing.
27469
- */
27470
- function sessionMutationOutcome(error) {
27471
- return error instanceof CodexSessionMutationError ? error.outcome : "outcome_unknown";
27472
- }
27473
- /**
27474
- * Decide what a failed queue mutation proved about delivery. Refusals raised by this module
27475
- * or undecidable queue failures are unknown once the remote effect may have started, and
27476
- * not delivered before that point.
27477
- * @param error - The thrown value from the queue port or a pre-effect check.
27478
- * @param effectStarted - Whether the remote effect had been issued when the error surfaced.
27479
- * @returns The outcome to settle durably.
27480
- */
27481
- function queueMutationOutcome(error, effectStarted = true) {
27482
- if (isUndecidableFailure(error)) return effectStarted ? "outcome_unknown" : "not_delivered";
27483
- return assertedQueueOutcome(error) ?? "not_delivered";
27484
- }
27485
- /**
27486
- * Recognise a failure that says nothing about the remote effect: a refusal raised by this module
27487
- * after the effect may have started, or a queue error whose code is itself undecidable.
27488
- * @param error - The thrown value.
27489
- * @returns Whether the remote outcome is undecidable from this error alone.
27490
- */
27491
- function isUndecidableFailure(error) {
27492
- return error instanceof CodexWorkhorseOperationsError || isUndecidableQueueError(error);
27493
- }
27494
- /**
27495
- * The delivery outcome a queue error asserts, when it asserts one.
27496
- * @param error - The thrown value.
27497
- * @returns The asserted outcome, or null when the error asserts none.
27498
- */
27499
- function assertedQueueOutcome(error) {
27500
- return error instanceof CodexWorkhorseQueueError ? error.outcome : null;
27501
- }
27502
- /**
27503
- * Recognise a queue error whose code means the remote outcome cannot be decided.
27504
- * @param error - The thrown value.
27505
- * @returns Whether the error is a queue error with an undecidable code.
27506
- */
27507
- function isUndecidableQueueError(error) {
27508
- return error instanceof CodexWorkhorseQueueError && UNDECIDABLE_QUEUE_CODES.has(error.code);
27509
- }
27510
- // src/runtime/workhorses/workhorse-operations/rules/internal.ts
27511
- const INPUT_LIMIT_BYTES = 4096;
27512
- const ATTENTION_FLAGS = /* @__PURE__ */ new Set(["waitingOnApproval", "waitingOnUserInput"]);
27513
- /** The fields that make two coordinator calls the same logical call. */
27514
- const CALL_IDENTITY_KEYS = [
27515
- "child",
27516
- "epoch",
27517
- "threadId",
27518
- "turnId",
27519
- "callId",
27520
- "namespace",
27521
- "tool",
27522
- "manifestHash"
27523
- ];
27524
- /**
27525
- * Freeze a value with its type preserved, so snapshots handed to callers stay immutable.
27526
- * @param value - The value to freeze.
27527
- * @returns The same value, frozen.
27528
- */
27529
- function freeze(value) {
27530
- return Object.freeze(value);
27531
- }
27532
- /**
27533
- * Trim a detail string to the input byte budget so an event never carries unbounded text.
27534
- * @param value - The detail text to bound.
27535
- * @returns The text unchanged when it fits, otherwise a byte-bounded prefix with an ellipsis.
27536
- */
27537
- function boundedDetail(value) {
27538
- if (Buffer.byteLength(value, "utf8") <= INPUT_LIMIT_BYTES) return value;
27539
- const suffix = "...";
27540
- const budget = INPUT_LIMIT_BYTES - Buffer.byteLength(suffix, "utf8");
27541
- let bytes = 0;
27542
- let prefix = "";
27543
- for (const character of value) {
27544
- const characterBytes = Buffer.byteLength(character, "utf8");
27545
- if (bytes + characterBytes > budget) break;
27546
- prefix += character;
27547
- bytes += characterBytes;
27548
- }
27549
- return `${prefix}${suffix}`;
27550
- }
27551
- /**
27552
- * Compare two coordinator calls field by field; a call is trusted only when every identity
27553
- * component matches the one the server is currently executing.
27554
- * @param left - One coordinator call.
27555
- * @param right - The other coordinator call.
27556
- * @returns Whether both calls name the same logical tool call.
27557
- */
27558
- function sameCall(left, right) {
27559
- return CALL_IDENTITY_KEYS.every((key) => left[key] === right[key]);
27560
- }
27561
- /**
27562
- * Compare two operation targets by child, epoch, thread and operation identity.
27563
- * @param left - One target.
27564
- * @param right - The other target.
27565
- * @returns Whether both targets name the same linked thread under the same ownership.
27566
- */
27567
- function sameTarget(left, right) {
27568
- return left.childId === right.childId && left.epoch === right.epoch && left.threadId === right.threadId && left.operationId === right.operationId;
27569
- }
27570
- /**
27571
- * Compare two bindings, including both linked targets.
27572
- * @param left - One binding.
27573
- * @param right - The other binding.
27574
- * @returns Whether both bindings link the same coordinator and workhorse under the same epoch.
27575
- */
27576
- function sameBinding$1(left, right) {
27577
- return left.childId === right.childId && left.epoch === right.epoch && sameTarget(left.coordinator, right.coordinator) && sameTarget(left.workhorse, right.workhorse);
27578
- }
27579
- /**
27580
- * Compare two bindings by their epoch and workhorse alone. An accepted operation belongs to its
27581
- * workhorse turn, and it follows that turn to the end even after a voice start replaces the
27582
- * coordinator that asked for it; what it reports then reaches no coordinator.
27583
- * @param left - One binding.
27584
- * @param right - The other binding.
27585
- * @returns Whether both bindings name the same workhorse under the same epoch.
27586
- */
27587
- function sameWorkhorse(left, right) {
27588
- return left.childId === right.childId && left.epoch === right.epoch && sameTarget(left.workhorse, right.workhorse);
27589
- }
27590
- /**
27591
- * Copy a target so later changes by the composition root cannot alter a captured operation.
27592
- * @param target - The live target.
27593
- * @returns A frozen copy.
27594
- */
27595
- function snapshotTarget(target) {
27596
- return freeze({ ...target });
27597
- }
27598
- /**
27599
- * Copy a binding and both of its targets for the lifetime of one operation.
27600
- * @param binding - The live binding.
27601
- * @returns A frozen copy with frozen targets.
27602
- */
27603
- function snapshotBinding(binding) {
27604
- return freeze({
27605
- childId: binding.childId,
27606
- epoch: binding.epoch,
27607
- coordinator: snapshotTarget(binding.coordinator),
27608
- workhorse: snapshotTarget(binding.workhorse)
27609
- });
27610
- }
27611
- /**
27612
- * Copy a coordinator call so the event correlation keeps the call as it was accepted.
27613
- * @param call - The live call.
27614
- * @returns A frozen copy.
27615
- */
27616
- function snapshotCall(call) {
27617
- return freeze({ ...call });
27618
- }
27619
- /**
27620
- * Resolve the wire RPC an operation will issue, which the durable record must name exactly.
27621
- * @param operation - The mutating workhorse operation.
27622
- * @param queueOperation - The queue mutation when the operation goes through the queue.
27623
- * @param rpcOverride - An explicit RPC when the caller already decided the route.
27624
- * @returns The RPC method name recorded for the operation.
27625
- */
27626
- function operationRpc(operation, queueOperation, rpcOverride) {
27627
- if (rpcOverride !== void 0) return rpcOverride;
27628
- if (operation === "delegate_to_workhorse") return "turn/start";
27629
- if (operation === "steer_workhorse") return "turn/steer";
27630
- if (queueOperation === void 0) throw new TypeError("queue mutation is required");
27631
- return `thread/queue/${queueOperation}`;
27632
- }
27633
- /**
27634
- * Refuse caller text that is empty or larger than the input byte budget.
27635
- * @param value - The caller-supplied text.
27636
- * @param label - How the text is named in the refusal.
27637
- * @param allowEmpty - Whether an empty string is acceptable.
27638
- */
27639
- function validateBoundedInput(value, label, allowEmpty = false) {
27640
- if (typeof value !== "string" || !allowEmpty && value.length === 0) throw operationError("invalid_input", `${label} must be nonempty text.`);
27641
- if (Buffer.byteLength(value, "utf8") > INPUT_LIMIT_BYTES) throw operationError("invalid_input", `${label} must be at most ${INPUT_LIMIT_BYTES} UTF-8 bytes.`);
27642
- }
27643
- /**
27644
- * Choose the operation identity for a mutation: the caller's when the dispatcher already owns
27645
- * the effect, otherwise a freshly minted one, and prove it is current before any effect.
27646
- * @param runtime - The operations runtime holding the operation authority.
27647
- * @param operation - The operation being identified, for the refusal message.
27648
- * @param candidate - The caller-supplied identity, if any.
27649
- * @returns The validated identity with its wire serialization.
27650
- */
27651
- function selectOperationIdentity(runtime, operation, candidate) {
27652
- try {
27653
- const operationId = candidate ?? runtime.options.operation.issuer.mintOperationId();
27654
- runtime.options.operation.validator.assertCurrentOperationId(operationId);
27655
- return Object.freeze({
27656
- operationId,
27657
- operationIdWire: runtime.options.operation.decoder.serializeOperationId(operationId)
27658
- });
27659
- } catch (error) {
27660
- throw operationError("invalid_input", `A current ${operation} identity was unavailable.`, {
27661
- operation,
27662
- cause: error
27663
- });
27664
- }
27665
- }
27666
- /**
27667
- * Read the single in-progress turn from a classification, if exactly one exists.
27668
- * @param classification - The classified linked thread.
27669
- * @returns The active turn identity, or null when none or several turns are in progress.
27670
- */
27671
- function activeTurnFromClassification(classification) {
27672
- if (classification.thread === null) return null;
27673
- const active = classification.thread.turns.filter((turn) => turn.status === "inProgress");
27674
- return active.length === 1 ? active[0].id : null;
27675
- }
27676
- /**
27677
- * Serialize a thread identity to the wire form used as a map key and in notifications.
27678
- * @param options - The operation options holding the identity decoder.
27679
- * @param threadId - The trusted thread identity.
27680
- * @returns The wire string.
27681
- */
27682
- function threadIdWire(options, threadId) {
27683
- return options.identity.decoder.serializeCodexIdentity(threadId);
27684
- }
27685
- /**
27686
- * Serialize a turn identity to the wire form found in notifications.
27687
- * @param options - The operation options holding the identity decoder.
27688
- * @param turnId - The trusted turn identity.
27689
- * @returns The wire string.
27690
- */
27691
- function turnIdWire(options, turnId) {
27692
- return options.identity.decoder.serializeCodexIdentity(turnId);
27693
- }
27694
- /**
27695
- * Adopt a raw turn identity from a notification through the trusted decoder.
27696
- * @param options - The operation options holding the identity decoder.
27697
- * @param value - The raw wire turn identity.
27698
- * @returns The trusted turn identity.
27699
- */
27700
- function turnIdFromRaw(options, value) {
27701
- const turnId = options.identity.decoder.adoptCodexResponseIdentities({ turnIds: [value] }).turnIds[0];
27702
- if (turnId === void 0) throw new TypeError("notification did not contain a turn identity");
27703
- return turnId;
27704
- }
27705
- /**
27706
- * Collect the client identities of the user messages in a turn; they are how a queued or
27707
- * started submission is matched back to the operation that sent it.
27708
- * @param turn - The turn from a turn lifecycle notification.
27709
- * @returns The client identities present on user messages.
27710
- */
27711
- function userMessageClientIds(turn) {
27712
- return turn.items.flatMap((item) => item.type === "userMessage" && item.clientId !== null ? [item.clientId] : []);
27713
- }
27714
- /**
27715
- * Project a queue snapshot to its submission identities.
27716
- * @param queue - The queue entries.
27717
- * @returns A frozen list of identities in queue order.
27718
- */
27719
- function queueIds(queue) {
27720
- return freeze(queue.map(({ id }) => id));
27721
- }
27722
28520
  // src/runtime/workhorses/workhorse-operations/services/event-publishing.ts
27723
28521
  /**
27724
28522
  * Project an operation's state to the correlation every event carries, so consumers can tie
@@ -27727,7 +28525,7 @@ function queueIds(queue) {
27727
28525
  * @returns The frozen correlation.
27728
28526
  */
27729
28527
  function correlationForState(state) {
27730
- return freeze({
28528
+ return freeze$3({
27731
28529
  operationId: state.operationId,
27732
28530
  childId: state.binding.childId,
27733
28531
  epoch: state.binding.epoch,
@@ -27750,22 +28548,22 @@ function correlationForState(state) {
27750
28548
  */
27751
28549
  function buildEvent(base, type, outcome) {
27752
28550
  switch (type) {
27753
- case "accepted": return freeze({
28551
+ case "accepted": return freeze$3({
27754
28552
  ...base,
27755
28553
  type,
27756
28554
  outcome: "pending"
27757
28555
  });
27758
- case "failed": return freeze({
28556
+ case "failed": return freeze$3({
27759
28557
  ...base,
27760
28558
  type,
27761
28559
  outcome: outcome === "not_delivered" ? "not_delivered" : "delivered"
27762
28560
  });
27763
- case "outcome_unknown": return freeze({
28561
+ case "outcome_unknown": return freeze$3({
27764
28562
  ...base,
27765
28563
  type,
27766
28564
  outcome: "outcome_unknown"
27767
28565
  });
27768
- default: return freeze({
28566
+ default: return freeze$3({
27769
28567
  ...base,
27770
28568
  type,
27771
28569
  outcome: "delivered"
@@ -28116,86 +28914,6 @@ function createWorkhorseEvents(options) {
28116
28914
  subscribe: publisher.subscribe
28117
28915
  };
28118
28916
  }
28119
- // src/runtime/workhorses/workhorse-operations/rules/link-provenance.ts
28120
- const WORKHORSE_CREATION_KIND = "create_thread";
28121
- const WORKHORSE_THREAD_SOURCE$1 = CODEX_SESSION_THREAD_SOURCE;
28122
- /**
28123
- * Check that a durable record's correlation names the target's child, epoch and operation.
28124
- * @param record - The committed epoch record.
28125
- * @param target - The operation target.
28126
- * @returns Whether the correlation matches.
28127
- */
28128
- function correlationMatchesTarget(record, target) {
28129
- return record.correlation.childId === target.childId && record.correlation.epoch === target.epoch && record.correlation.operationId === target.operationId;
28130
- }
28131
- /**
28132
- * Check that a durable record's provenance names the target's thread under the same ownership
28133
- * and carries a confirmed thread source.
28134
- * @param record - The committed epoch record.
28135
- * @param target - The operation target.
28136
- * @returns Whether the provenance matches.
28137
- */
28138
- function provenanceMatchesTarget(record, target) {
28139
- return record.provenance.childId === target.childId && record.provenance.epoch === target.epoch && record.provenance.threadId === target.threadId && record.provenance.threadSource !== null;
28140
- }
28141
- /**
28142
- * Check that a durable record proves ownership of exactly the operation target.
28143
- * @param record - The committed epoch record.
28144
- * @param target - The operation target.
28145
- * @returns Whether both correlation and provenance match.
28146
- */
28147
- function recordMatchesTarget(record, target) {
28148
- return correlationMatchesTarget(record, target) && provenanceMatchesTarget(record, target);
28149
- }
28150
- /**
28151
- * Check that an executable link still names the captured target.
28152
- * @param link - The executable link from the classifier.
28153
- * @param target - The operation target.
28154
- * @returns Whether child, epoch and thread agree.
28155
- */
28156
- function linkMatchesTarget(link, target) {
28157
- return link.childId === target.childId && link.epoch === target.epoch && link.threadId === target.threadId;
28158
- }
28159
- /**
28160
- * Check that the classification carries a committed, delivered proof for the target.
28161
- * @param classification - The classified link.
28162
- * @param target - The operation target.
28163
- * @returns Whether the proof is present and canonical for the target.
28164
- */
28165
- function proofMatchesTarget(classification, target) {
28166
- const proof = classification.proof;
28167
- return proof !== null && recordMatchesTarget(proof.record, target) && proof.record.status === "committed" && proof.record.outcome === "delivered";
28168
- }
28169
- /**
28170
- * Refuse any link that is not executable for the exact target with current durable proof.
28171
- * Mutations run only against a link the classifier and the epoch store both vouch for.
28172
- * @param classification - The classified link.
28173
- * @param target - The operation target the link must match.
28174
- * @param label - How the link is named in the refusal.
28175
- */
28176
- function assertExecutableClassification(classification, target, label) {
28177
- const link = classification.link;
28178
- if (link.state !== "executable") {
28179
- const reason = link.reason;
28180
- throw operationError(mapLinkReason(reason), `${label} is inspect-only: ${reason}. Re-read the current linked state before retrying.`);
28181
- }
28182
- if (!linkMatchesTarget(link, target) || !proofMatchesTarget(classification, target)) throw operationError("unknown_provenance", `${label} lost its current executable provenance; inspect the link before retrying.`);
28183
- }
28184
- /**
28185
- * Recognise the workhorse this server created, the only thread whose queue it may touch.
28186
- * @param classification - The classified workhorse link.
28187
- * @returns Whether the link is executable, app-server sourced and proven by a creation record.
28188
- */
28189
- function isCreatedWorkhorse(classification) {
28190
- return classification.link.state === "executable" && classification.link.source === WORKHORSE_THREAD_SOURCE$1 && classification.proof?.record.operation.kind === WORKHORSE_CREATION_KIND && classification.proof.record.provenance.threadSource === WORKHORSE_THREAD_SOURCE$1;
28191
- }
28192
- /**
28193
- * Refuse queue access to any thread other than the created, proven workhorse.
28194
- * @param classification - The classified workhorse link.
28195
- */
28196
- function assertCreatedWorkhorse(classification) {
28197
- if (!isCreatedWorkhorse(classification)) throw operationError("unknown_provenance", "Queue access is restricted to the created workhorse with proven ownership.");
28198
- }
28199
28917
  // src/runtime/workhorses/workhorse-operations/services/validation.ts
28200
28918
  /**
28201
28919
  * Check that both linked targets share the binding's child and epoch; a binding assembled
@@ -28276,7 +28994,7 @@ function createWorkhorseValidation(options) {
28276
28994
  if (current === null) throw operationError("not_ready", "The workhorse link is no longer available.");
28277
28995
  if (current.childId !== binding.childId) throw operationError("stale_child", "The workhorse child was replaced during the operation.");
28278
28996
  if (current.epoch !== binding.epoch) throw operationError("prior_epoch", "The workhorse link belongs to a prior epoch.");
28279
- if (!sameBinding$1(current, binding)) throw operationError("stale_link", "The coordinator or workhorse link changed during the operation.");
28997
+ if (!sameBinding$4(current, binding)) throw operationError("stale_link", "The coordinator or workhorse link changed during the operation.");
28280
28998
  };
28281
28999
  /**
28282
29000
  * Refuse a coordinator call that is not the trusted, current call for the named tool.
@@ -28289,7 +29007,7 @@ function createWorkhorseValidation(options) {
28289
29007
  if (!callNamesTool(options.tools, parsed, tool)) throw operationError("invalid_call", `The coordinator call is not for ${tool}.`);
28290
29008
  if (binding !== void 0 && !callBelongsToBinding(parsed, binding)) throw operationError("invalid_call", "The coordinator call does not belong to the captured child, epoch, and coordinator thread.");
28291
29009
  const current = readCurrentCall(options);
28292
- if (current === null || !sameCall(parsed, current)) throw operationError("invalid_call", "The coordinator call is no longer the current executing call.");
29010
+ if (current === null || !sameCall$1(parsed, current)) throw operationError("invalid_call", "The coordinator call is no longer the current executing call.");
28293
29011
  };
28294
29012
  /**
28295
29013
  * Classify both linked threads and require executable provenance, re-checking the binding
@@ -28530,46 +29248,6 @@ function mutationErrorCode$1(outcome) {
28530
29248
  return outcome === "outcome_unknown" ? "outcome_unknown" : "transport_failure";
28531
29249
  }
28532
29250
  /**
28533
- * Record the workhorse's active turn from a fresh classification for later notifications.
28534
- * @param runtime - The operations runtime.
28535
- * @param threadId - The workhorse thread.
28536
- * @param classification - The fresh workhorse classification.
28537
- * @returns The active turn identity, or null when none is in progress.
28538
- */
28539
- function activeTurnId(runtime, threadId, classification) {
28540
- const current = activeTurnFromClassification(classification);
28541
- const key = threadIdWire(runtime.options, threadId);
28542
- if (current === null) {
28543
- runtime.activeTurns.delete(key);
28544
- return null;
28545
- }
28546
- runtime.activeTurns.set(key, current);
28547
- return current;
28548
- }
28549
- /**
28550
- * Create the inspect operation: a read of link status, active turn and queue that never
28551
- * mutates anything.
28552
- * @param runtime - The operations runtime.
28553
- * @returns The inspect operation.
28554
- */
28555
- function createInspect(runtime) {
28556
- return (request) => runtime.enqueue(async () => {
28557
- const binding = runtime.currentBinding();
28558
- const result = isCreatedWorkhorse((await runtime.classify(binding, request.call, "inspect_workhorse")).workhorse) ? await runtime.options.queue.list() : {
28559
- operation: "list",
28560
- queue: []
28561
- };
28562
- const final = await runtime.classify(binding, request.call, "inspect_workhorse");
28563
- const currentTurnId = activeTurnId(runtime, binding.workhorse.threadId, final.workhorse);
28564
- return freeze({
28565
- threadId: binding.workhorse.threadId,
28566
- status: final.workhorse.link.status,
28567
- activeTurnId: currentTurnId,
28568
- queuedSubmissionIds: queueIds(result.queue)
28569
- });
28570
- });
28571
- }
28572
- /**
28573
29251
  * Read the client identity of the exact submission a queue start is about to start; the
28574
29252
  * baseline the queue module validated must be the one the caller asked for.
28575
29253
  * @param context - The queue module's pre-effect context.
@@ -28794,7 +29472,7 @@ async function mutateQueue(runtime, request, binding, validated, operationId, op
28794
29472
  outcome,
28795
29473
  operationId
28796
29474
  });
28797
- return freeze({
29475
+ return freeze$3({
28798
29476
  operation: request.operation,
28799
29477
  queuedSubmissionIds: queueIds(result.queue)
28800
29478
  });
@@ -28815,7 +29493,7 @@ function createManageQueue(runtime) {
28815
29493
  runtime.assertCurrentBinding(binding);
28816
29494
  await runtime.classify(binding, request.call, "manage_workhorse_queue");
28817
29495
  runtime.reconcileUnknownQueue(result.queue);
28818
- return freeze({
29496
+ return freeze$3({
28819
29497
  operation: "list",
28820
29498
  queuedSubmissionIds: queueIds(result.queue)
28821
29499
  });
@@ -28835,12 +29513,43 @@ function createManageQueue(runtime) {
28835
29513
  }
28836
29514
  // src/runtime/workhorses/workhorse-operations/operations/steer.ts
28837
29515
  /**
28838
- * Refuse to steer unless the workhorse is active on exactly the turn the caller captured.
28839
- * @param request - The steer request.
29516
+ * The turn Codex lists as running on the workhorse thread.
29517
+ * @param runtime - The operations runtime.
29518
+ * @param threadId - The workhorse thread.
29519
+ * @returns The running turn, or null when none runs.
29520
+ */
29521
+ async function readRunningTurn(runtime, threadId) {
29522
+ try {
29523
+ return await readActiveTurn(runtime, threadId);
29524
+ } catch (error) {
29525
+ throw operationError("transport_failure", "The workhorse turns could not be read.", { cause: error });
29526
+ }
29527
+ }
29528
+ /**
29529
+ * The workhorse turn a steer targets: the one Codex lists as running on the workhorse thread. A
29530
+ * thread summary carries no turns, and the coordinator's own turn is never the target.
29531
+ * @param runtime - The operations runtime.
28840
29532
  * @param classification - The fresh classification.
29533
+ * @returns The running workhorse turn.
28841
29534
  */
28842
- function assertExpectedTurn(request, classification) {
28843
- if (classification.workhorse.link.status !== "active" || activeTurnFromClassification(classification.workhorse) !== request.expectedTurnId) throw operationError("busy", "Steer requires the exact currently active workhorse turn.");
29535
+ async function runningWorkhorseTurn(runtime, classification) {
29536
+ if (classification.workhorse.link.status !== "active") throw operationError("busy", "Steer requires a running workhorse turn.");
29537
+ const turnId = await readRunningTurn(runtime, classification.binding.workhorse.threadId);
29538
+ if (turnId === null) throw operationError("busy", "Steer requires a running workhorse turn.");
29539
+ return turnId;
29540
+ }
29541
+ /**
29542
+ * Refuse to steer unless the link is unchanged and the workhorse still runs exactly the turn the
29543
+ * steer targets. The turn is read first and the link classified after it, so a link that changes
29544
+ * while the turn is read is still refused.
29545
+ * @param runtime - The operations runtime.
29546
+ * @param request - The steer request.
29547
+ * @param state - The staged operation state.
29548
+ * @param target - The turn the steer targets.
29549
+ */
29550
+ async function assertTargetTurn(runtime, request, state, target) {
29551
+ const running = await readRunningTurn(runtime, state.binding.workhorse.threadId);
29552
+ if ((await runtime.classify(state.binding, request.call, "steer_workhorse")).workhorse.link.status !== "active" || running !== target) throw operationError("busy", "The workhorse turn changed before the steer was delivered.");
28844
29553
  }
28845
29554
  /**
28846
29555
  * Re-check authority after staging and before delivery; a change settles the operation as not
@@ -28848,11 +29557,12 @@ function assertExpectedTurn(request, classification) {
28848
29557
  * @param runtime - The operations runtime.
28849
29558
  * @param request - The steer request.
28850
29559
  * @param state - The staged operation state.
29560
+ * @param target - The workhorse turn the steer targets.
28851
29561
  * @param message - The message for the refusal.
28852
29562
  */
28853
- async function revalidateSteer(runtime, request, state, message) {
29563
+ async function revalidateSteer(runtime, request, state, target, message) {
28854
29564
  try {
28855
- assertExpectedTurn(request, await runtime.classify(state.binding, request.call, "steer_workhorse"));
29565
+ await assertTargetTurn(runtime, request, state, target);
28856
29566
  } catch (error) {
28857
29567
  const outcome = runtime.settleDurable(state, "not_delivered", messageOf(error));
28858
29568
  runtime.terminal(state, "failed", [], messageOf(error));
@@ -28870,9 +29580,10 @@ async function revalidateSteer(runtime, request, state, message) {
28870
29580
  * @param runtime - The operations runtime.
28871
29581
  * @param request - The steer request.
28872
29582
  * @param state - The staged operation state.
29583
+ * @param target - The workhorse turn the steer targets.
28873
29584
  * @returns The turn/steer parameters.
28874
29585
  */
28875
- function buildSteerParams(runtime, request, state) {
29586
+ function buildSteerParams(runtime, request, state, target) {
28876
29587
  try {
28877
29588
  const context = runtime.options.contextFor({
28878
29589
  operationId: state.operationId,
@@ -28885,7 +29596,7 @@ function buildSteerParams(runtime, request, state) {
28885
29596
  clientUserMessageId: state.operationIdWire,
28886
29597
  input: [createTextUserInput(request.input)],
28887
29598
  additionalContext: createWorkbenchAdditionalContext(context, runtime.options.contextCodec),
28888
- expectedTurnId: request.expectedTurnId
29599
+ expectedTurnId: target
28889
29600
  };
28890
29601
  } catch (error) {
28891
29602
  runtime.settleDurable(state, "not_delivered", "The steer body was invalid.");
@@ -28902,11 +29613,11 @@ function buildSteerParams(runtime, request, state) {
28902
29613
  * Record the steered turn as active and emit `started` once.
28903
29614
  * @param runtime - The operations runtime.
28904
29615
  * @param state - The delivered operation state.
28905
- * @param request - The steer request.
29616
+ * @param target - The steered workhorse turn.
28906
29617
  */
28907
- function publishSteerStarted(runtime, state, request) {
29618
+ function publishSteerStarted(runtime, state, target) {
28908
29619
  if (state.terminalEmitted) return;
28909
- runtime.activeTurns.set(threadIdWire(runtime.options, state.workhorseThreadId), request.expectedTurnId);
29620
+ runtime.activeTurns.set(threadIdWire(runtime.options, state.workhorseThreadId), target);
28910
29621
  if (!state.startedEmitted) {
28911
29622
  state.startedEmitted = true;
28912
29623
  runtime.emit(state, "started", "delivered", []);
@@ -28935,32 +29646,34 @@ function settleSteerFailure(runtime, state, error) {
28935
29646
  * @returns The steered turn with its delivery.
28936
29647
  */
28937
29648
  async function deliverSteer(runtime, request, state, params) {
29649
+ const target = params.expectedTurnId;
28938
29650
  try {
28939
- if ((await runtime.options.session.turnSteer(params)).turnId !== request.expectedTurnId) throw new TypeError("turn/steer returned a different turn identity");
29651
+ if ((await runtime.options.session.turnSteer(params)).turnId !== target) throw new TypeError("turn/steer returned a different turn identity");
28940
29652
  await runtime.classify(state.binding, request.call, "steer_workhorse");
28941
29653
  const outcome = runtime.settleDurable(state, "delivered", null);
28942
29654
  if (outcome !== "delivered") {
28943
29655
  runtime.emit(state, "outcome_unknown", outcome, [], "The steer response could not be durably committed.");
28944
29656
  return Object.freeze({
28945
- turnId: request.expectedTurnId,
29657
+ turnId: target,
28946
29658
  delivery: outcome
28947
29659
  });
28948
29660
  }
28949
- publishSteerStarted(runtime, state, request);
29661
+ publishSteerStarted(runtime, state, target);
28950
29662
  return Object.freeze({
28951
- turnId: request.expectedTurnId,
29663
+ turnId: target,
28952
29664
  delivery: "delivered"
28953
29665
  });
28954
29666
  } catch (error) {
28955
29667
  const delivery = settleSteerFailure(runtime, state, error);
28956
29668
  return Object.freeze({
28957
- turnId: request.expectedTurnId,
29669
+ turnId: target,
28958
29670
  delivery
28959
29671
  });
28960
29672
  }
28961
29673
  }
28962
29674
  /**
28963
- * Create the steer operation: inject input into the exact active workhorse turn.
29675
+ * Create the steer operation: inject input into the turn the workhorse runs now, as Codex lists
29676
+ * it, and let turn/steer refuse that turn if it ended meanwhile.
28964
29677
  * @param runtime - The operations runtime.
28965
29678
  * @returns The steer operation.
28966
29679
  */
@@ -28978,7 +29691,7 @@ function createSteer(runtime) {
28978
29691
  return runtime.enqueue(async () => {
28979
29692
  const binding = runtime.currentBinding();
28980
29693
  const validated = await runtime.classify(binding, request.call, "steer_workhorse");
28981
- assertExpectedTurn(request, validated);
29694
+ const target = await runningWorkhorseTurn(runtime, validated);
28982
29695
  const state = runtime.stage({
28983
29696
  operationId,
28984
29697
  operationIdWire,
@@ -28989,10 +29702,10 @@ function createSteer(runtime) {
28989
29702
  workhorse: validated.workhorse,
28990
29703
  clientUserMessageId: operationIdWire
28991
29704
  });
28992
- state.turnId = request.expectedTurnId;
28993
- await revalidateSteer(runtime, request, state, "Steer authority changed after staging.");
28994
- const params = buildSteerParams(runtime, request, state);
28995
- await revalidateSteer(runtime, request, state, "Steer authority changed before delivery.");
29705
+ state.turnId = target;
29706
+ await revalidateSteer(runtime, request, state, target, "Steer authority changed after staging.");
29707
+ const params = buildSteerParams(runtime, request, state, target);
29708
+ await revalidateSteer(runtime, request, state, target, "Steer authority changed before delivery.");
28996
29709
  return deliverSteer(runtime, request, state, params);
28997
29710
  });
28998
29711
  };
@@ -32174,16 +32887,20 @@ function endTabSession(session, ending) {
32174
32887
  // src/server/sessions/services/workhorses.ts
32175
32888
  /**
32176
32889
  * A workhorse's state before anything was read into it.
32890
+ * @param stopAskers The coordinator turns that asked its tab session for a stop.
32177
32891
  * @returns The state.
32178
32892
  */
32179
- function freshWorkhorseState() {
32893
+ function freshWorkhorseState(stopAskers = /* @__PURE__ */ new Set()) {
32180
32894
  return {
32181
32895
  queue: {
32182
32896
  kind: "codex_queue",
32183
32897
  submissions: null
32184
32898
  },
32185
32899
  queueThreadId: null,
32186
- activeTurn: null
32900
+ activeTurn: null,
32901
+ stop: null,
32902
+ stopAskers,
32903
+ admitted: /* @__PURE__ */ new Set()
32187
32904
  };
32188
32905
  }
32189
32906
  /**
@@ -32228,30 +32945,6 @@ function noteActiveTurn(workhorse, event, decoder) {
32228
32945
  turnId: decoder.adoptTurnId(notification.params.turn.id)
32229
32946
  };
32230
32947
  }
32231
- /**
32232
- * Stop what workhorses are running: interrupt the turn each one runs, and say what each did. A
32233
- * workhorse with no running turn has nothing to interrupt.
32234
- * @param workhorses The workhorses to stop.
32235
- * @param session Interrupts a turn.
32236
- * @returns What each one did, in the order given.
32237
- */
32238
- async function stopWorkhorses(workhorses, session) {
32239
- return Promise.all(workhorses.map(async ({ checkout, state }) => {
32240
- const running = state.activeTurn;
32241
- if (running === null) return {
32242
- checkout,
32243
- outcome: "idle"
32244
- };
32245
- await session.turnInterrupt({
32246
- threadId: running.threadId,
32247
- turnId: running.turnId
32248
- });
32249
- return {
32250
- checkout,
32251
- outcome: "interrupted"
32252
- };
32253
- }));
32254
- }
32255
32948
  // src/server/sessions/services/sessions.ts
32256
32949
  /**
32257
32950
  * A session's state before anything was read into it.
@@ -32265,7 +32958,8 @@ function freshState() {
32265
32958
  threads: /* @__PURE__ */ new Set(),
32266
32959
  voiceTrace: sessionVoiceStartTrace(),
32267
32960
  voiceCheckout: null,
32268
- phase: "live"
32961
+ phase: "live",
32962
+ stopAskers: /* @__PURE__ */ new Set()
32269
32963
  };
32270
32964
  }
32271
32965
  /**
@@ -32363,7 +33057,7 @@ function createCodexWorkbenchSessions(options) {
32363
33057
  const buildWorkhorse = (session, workhorses, fanOut, checkout) => {
32364
33058
  assertLive(session, "start no workhorse");
32365
33059
  const key = workhorseLinkKey(session.id, checkout);
32366
- const state = freshWorkhorseState();
33060
+ const state = freshWorkhorseState(session.state.stopAskers);
32367
33061
  let workhorse = null;
32368
33062
  /**
32369
33063
  * This workhorse, once it is built.
@@ -32373,7 +33067,7 @@ function createCodexWorkbenchSessions(options) {
32373
33067
  if (workhorse === null) throw new Error(`The workhorse of ${checkout} is still being built.`);
32374
33068
  return workhorse;
32375
33069
  };
32376
- const built = options.buildWorkhorse({
33070
+ const built = guardWorkhorse(self, options.buildWorkhorse({
32377
33071
  session,
32378
33072
  checkout,
32379
33073
  key,
@@ -32410,7 +33104,7 @@ function createCodexWorkbenchSessions(options) {
32410
33104
  releaseThread(session, threadId);
32411
33105
  return unload;
32412
33106
  }
32413
- });
33107
+ }));
32414
33108
  workhorse = Object.freeze({
32415
33109
  checkout,
32416
33110
  key,
@@ -32466,11 +33160,15 @@ function createCodexWorkbenchSessions(options) {
32466
33160
  */
32467
33161
  const voiceWorkhorse = () => state.voiceCheckout === null ? null : workhorses.get(state.voiceCheckout) ?? null;
32468
33162
  /**
32469
- * Stop the workhorse of one checkout, or every one of the tab.
33163
+ * Stop the work tree of the workhorse of one checkout, or of every one of the tab.
32470
33164
  * @param checkout The checkout, or null for every workhorse.
32471
- * @returns What each stopped workhorse did.
33165
+ * @param askedBy The coordinator turn that asked for the stop, or null for the Stop control.
33166
+ * @returns What each stop observed, in the order the workhorses were built.
32472
33167
  */
32473
- const stopWork = (checkout) => stopWorkhorses([...workhorses.values()].filter((candidate) => checkout === null || candidate.checkout === checkout), options.session);
33168
+ const stopWork = (checkout, askedBy = null) => {
33169
+ if (askedBy !== null) state.stopAskers.add(askedBy);
33170
+ return Promise.all([...workhorses.values()].filter((candidate) => checkout === null || candidate.checkout === checkout).map((candidate) => stopWorkTree(candidate, options.session, askedBy, options.stopClock)));
33171
+ };
32474
33172
  const built = options.build({
32475
33173
  id,
32476
33174
  state,
@@ -33299,6 +33997,16 @@ function browserLeaseThreadId(context) {
33299
33997
  * @returns The actions.
33300
33998
  */
33301
33999
  function createServerCanonicalTextActions(options) {
34000
+ /**
34001
+ * Refuse a typed message whose thread the chat's workhorse left since the command named it, as
34002
+ * New conversation does. It runs with no await before the request to Codex, so a link change
34003
+ * that completed while the command read the thread is always seen.
34004
+ * @param context The chat and the link it named.
34005
+ * @param threadId The thread the command names.
34006
+ */
34007
+ const assertLinkStands = (context, threadId) => {
34008
+ if (options.workhorseThread(context) !== threadId) throw new CodexWorkbenchGatewayError("link_changed", "The workhorse moved to another conversation while this message waited; read it again.", { outcome: "not_delivered" });
34009
+ };
33302
34010
  /**
33303
34011
  * A fresh operation identity, and how it is spelled in the wire field Codex
33304
34012
  * carries it back in.
@@ -33338,9 +34046,12 @@ function createServerCanonicalTextActions(options) {
33338
34046
  }, options.contextCodec);
33339
34047
  return {
33340
34048
  outcome: "delivered",
33341
- turnId: (await options.session.turnStart({
33342
- ...canonical,
33343
- threadId
34049
+ turnId: (await options.admitNewWork(context, () => {
34050
+ assertLinkStands(context, threadId);
34051
+ return options.session.turnStart({
34052
+ ...canonical,
34053
+ threadId
34054
+ });
33344
34055
  })).turn.id
33345
34056
  };
33346
34057
  },
@@ -33369,24 +34080,26 @@ function createServerCanonicalTextActions(options) {
33369
34080
  rpc: "turn/steer"
33370
34081
  })
33371
34082
  }, options.contextCodec);
33372
- await options.session.turnSteer({
33373
- ...canonical,
33374
- threadId,
33375
- expectedTurnId: command.turnId
34083
+ await options.admitNewWork(context, () => {
34084
+ assertLinkStands(context, threadId);
34085
+ return options.session.turnSteer({
34086
+ ...canonical,
34087
+ threadId,
34088
+ expectedTurnId: command.turnId
34089
+ });
33376
34090
  });
33377
34091
  return { outcome: "delivered" };
33378
34092
  },
33379
34093
  /**
33380
- * Stop the turn that is running on the workhorse of the chat's checkout. The gateway admits
33381
- * the command only when its thread is the link of that workhorse.
33382
- * @param command The thread and the turn.
34094
+ * The Stop control: stop the whole work tree of the workhorse of the chat's checkout, the
34095
+ * same stop that a spoken stop runs. The gateway admits the command only when its thread is
34096
+ * the link of that workhorse. A stop that did not show all work ended says so.
34097
+ * @param _command The thread and the turn the control was offered for.
34098
+ * @param context The chat and the link it named.
33383
34099
  * @returns The browser outcome.
33384
34100
  */
33385
- interrupt: async (command) => {
33386
- await options.session.turnInterrupt({
33387
- threadId: command.threadId,
33388
- turnId: command.turnId
33389
- });
34101
+ interrupt: async (_command, context) => {
34102
+ if ((await options.stopWork(context)).some(({ outcome }) => outcome === "partial" || outcome === "unconfirmed")) throw new CodexWorkbenchGatewayError("stop_unconfirmed", "The stop did not show that all work of the workhorse ended.", { outcome: "delivered" });
33390
34103
  return { outcome: "delivered" };
33391
34104
  }
33392
34105
  });
@@ -34811,7 +35524,26 @@ create: async (command, context) => {
34811
35524
  identity: components.identity,
34812
35525
  session: components.session,
34813
35526
  contextForOperation: input.contextForOperation,
34814
- contextCodec: input.contextCodec
35527
+ contextCodec: input.contextCodec,
35528
+ /**
35529
+ * Send a typed message as work admitted to the chat's workhorse.
35530
+ * @param context The chat.
35531
+ * @param start The message's request to Codex.
35532
+ * @returns What Codex answered.
35533
+ */
35534
+ admitNewWork: (context, start) => admitWork(workhorseOf(context), null, start),
35535
+ /**
35536
+ * The thread the chat's workhorse is linked to now.
35537
+ * @param context The chat.
35538
+ * @returns The thread, or null while it has none.
35539
+ */
35540
+ workhorseThread: (context) => workhorseOf(context).components.workhorse.snapshot().threadId,
35541
+ /**
35542
+ * Stop the work tree of the chat's workhorse.
35543
+ * @param context The chat.
35544
+ * @returns What the stop observed.
35545
+ */
35546
+ stopWork: (context) => sessionOf(context).stopWork(context.checkout)
34815
35547
  }),
34816
35548
  queue: {
34817
35549
  /**
@@ -36807,12 +37539,7 @@ function coordinatorBindings(context) {
36807
37539
  * The coordinator call in flight.
36808
37540
  * @returns The call, or null.
36809
37541
  */
36810
- currentCall: () => state.currentCoordinatorCall,
36811
- /**
36812
- * The turn that call is expected to be running.
36813
- * @returns The turn, or null.
36814
- */
36815
- expectedTurnId: () => state.currentCoordinatorCall?.turnId ?? null
37542
+ currentCall: () => state.currentCoordinatorCall
36816
37543
  },
36817
37544
  /**
36818
37545
  * The workhorse of the checkout a call names, and the binding it shares with the
@@ -36832,14 +37559,21 @@ function coordinatorBindings(context) {
36832
37559
  workhorse: workhorse.components.workhorse,
36833
37560
  coordinator: created.coordinator
36834
37561
  }, shared.epoch),
36835
- operations: workhorse.components.operations
37562
+ operations: workhorse.components.operations,
37563
+ /**
37564
+ * Where this workhorse's last stop stands.
37565
+ * @returns It, or null before any stop.
37566
+ */
37567
+ lastStop: () => stopReport(workhorse)
36836
37568
  };
36837
37569
  },
36838
37570
  /**
36839
- * Stop every workhorse of this tab session: a spoken stop speaks for the whole app.
36840
- * @returns What each one did.
37571
+ * Stop the work tree of every workhorse of this tab session: a spoken stop speaks for the
37572
+ * whole app.
37573
+ * @param askedBy The coordinator turn whose call asked for it.
37574
+ * @returns What each stop observed.
36841
37575
  */
36842
- stopWork: () => scope.stopWork(null)
37576
+ stopWork: (askedBy) => scope.stopWork(null, askedBy)
36843
37577
  }),
36844
37578
  coordinatorCall: {
36845
37579
  /**