@humain/humain-code-contracts 0.4.4 → 0.4.6
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/CHANGELOG.md +17 -0
- package/dist/flow-common.d.ts +3 -3
- package/dist/flow-common.d.ts.map +1 -1
- package/dist/flow-common.js +4 -0
- package/dist/flow-common.js.map +1 -1
- package/dist/flow-control.d.ts +3 -3
- package/dist/flow-events.d.ts +5 -5
- package/dist/flow-events.js +1 -1
- package/dist/flow-events.js.map +1 -1
- package/dist/flow-sizing.d.ts +3 -1
- package/dist/flow-sizing.d.ts.map +1 -1
- package/dist/flow-sizing.js +32 -19
- package/dist/flow-sizing.js.map +1 -1
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +2 -0
- package/dist/rpc.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.4.6] - 2026-10-11
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- `classifyPromptSignals` uses policy `unified-regex-v5` (`UNIFIED_CLASSIFIER_POLICY_ID`): entire hello-world starter requests classify quick, British `colour` bounded edits, multi-section/multi-service complexity, and high-risk recognition of migrating a database schema. Intent lanes and the frozen corpus are preserved.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Each classification result carries `depthReason` (`PromptDepthReason`), a string-union value naming the first decisive rule, never prompt content (additive).
|
|
12
|
+
|
|
13
|
+
## [0.4.5] - 2026-10-11
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- `route_bound.binding` accepts `lead_selected` (a lead's explicit model choice for a nested subagent).
|
|
18
|
+
- Flow failure and RPC reason classes accept `review_verdict_missing` and `verification_unavailable` (additive).
|
|
19
|
+
|
|
3
20
|
## [0.4.4] - 2026-10-10
|
|
4
21
|
|
|
5
22
|
### Changed
|
package/dist/flow-common.d.ts
CHANGED
|
@@ -58,10 +58,10 @@ export declare const partialByRole: <T extends TSchema>(schema: T) => Type.TObje
|
|
|
58
58
|
export declare const FLOW_SIZES: readonly ["small", "medium", "large"];
|
|
59
59
|
export type FlowSize = (typeof FLOW_SIZES)[number];
|
|
60
60
|
export declare const FlowSizeSchema: TUnion<[TLiteral<"small">, TLiteral<"medium">, TLiteral<"large">]>;
|
|
61
|
-
export declare const FLOW_FAILURE_CLASSES: readonly ["provider_error", "rate_limit", "timeout", "check_failed", "review_rejected", "qa_failed", "budget_stop", "cancelled", "crash", "unsafe_scope", "stalled", "config_invalid", "internal"];
|
|
61
|
+
export declare const FLOW_FAILURE_CLASSES: readonly ["provider_error", "rate_limit", "timeout", "check_failed", "review_rejected", "qa_failed", "budget_stop", "cancelled", "crash", "unsafe_scope", "stalled", "config_invalid", "internal", "review_verdict_missing", "verification_unavailable"];
|
|
62
62
|
export type FlowFailureClass = (typeof FLOW_FAILURE_CLASSES)[number];
|
|
63
|
-
export declare const FlowFailureClassSchema: TUnion<[TLiteral<"provider_error">, TLiteral<"rate_limit">, TLiteral<"timeout">, TLiteral<"check_failed">, TLiteral<"review_rejected">, TLiteral<"qa_failed">, TLiteral<"budget_stop">, TLiteral<"cancelled">, TLiteral<"crash">, TLiteral<"unsafe_scope">, TLiteral<"stalled">, TLiteral<"config_invalid">, TLiteral<"internal">]>;
|
|
64
|
-
export declare const FlowReasonClassSchema: TUnion<[TUnion<[TLiteral<"provider_error">, TLiteral<"rate_limit">, TLiteral<"timeout">, TLiteral<"check_failed">, TLiteral<"review_rejected">, TLiteral<"qa_failed">, TLiteral<"budget_stop">, TLiteral<"cancelled">, TLiteral<"crash">, TLiteral<"unsafe_scope">, TLiteral<"stalled">, TLiteral<"config_invalid">, TLiteral<"internal">]>, TLiteral<"size_underestimated">]>;
|
|
63
|
+
export declare const FlowFailureClassSchema: TUnion<[TLiteral<"provider_error">, TLiteral<"rate_limit">, TLiteral<"timeout">, TLiteral<"check_failed">, TLiteral<"review_rejected">, TLiteral<"qa_failed">, TLiteral<"budget_stop">, TLiteral<"cancelled">, TLiteral<"crash">, TLiteral<"unsafe_scope">, TLiteral<"stalled">, TLiteral<"config_invalid">, TLiteral<"internal">, TLiteral<"review_verdict_missing">, TLiteral<"verification_unavailable">]>;
|
|
64
|
+
export declare const FlowReasonClassSchema: TUnion<[TUnion<[TLiteral<"provider_error">, TLiteral<"rate_limit">, TLiteral<"timeout">, TLiteral<"check_failed">, TLiteral<"review_rejected">, TLiteral<"qa_failed">, TLiteral<"budget_stop">, TLiteral<"cancelled">, TLiteral<"crash">, TLiteral<"unsafe_scope">, TLiteral<"stalled">, TLiteral<"config_invalid">, TLiteral<"internal">, TLiteral<"review_verdict_missing">, TLiteral<"verification_unavailable">]>, TLiteral<"size_underestimated">]>;
|
|
65
65
|
export type FlowReasonClass = Static<typeof FlowReasonClassSchema>;
|
|
66
66
|
export declare const FlowProfileRefSchema: Type.TObject<{
|
|
67
67
|
readonly id: Type.TString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow-common.d.ts","sourceRoot":"","sources":["../src/flow-common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,QAAQ,EAAE,KAAK,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAGtF;;;GAGG;AAEH,eAAO,MAAM,eAAe,kCAAkC,CAAC;AAC/D,gHAAgH;AAChH,eAAO,MAAM,qBAAqB,oEAAoE,CAAC;AACvG,eAAO,MAAM,mBAAmB,mBAAmB,CAAC;AAIpD,eAAO,MAAM,yBAAyB;aACrC,eAAe,EAAE,sBAAsB;aACvC,iBAAiB,EAAE,4BAA4B;aAC/C,aAAa,EAAE,oBAAoB;aACnC,eAAe,EAAE,8BAA8B;aAC/C,eAAe,EAAE,8BAA8B;aAC/C,cAAc,EAAE,qBAAqB;aACrC,eAAe,EAAE,sBAAsB;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AAC,QAAQ,EAAE,OAAO,KAAK,QAAQ,IAAI,CAAC,GAC5C,CAAC,CAIH;AAED,oHAAoH;AACpH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,qBAAqB,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAMxF;AAED,wBAAgB,WAAW,CAAC,CAAC,SAAS,OAAO,EAAE,MAAM,EAAE,CAAC,4JAEvD;AAED,wBAAgB,QAAQ,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,SAAS,YAAY,EAAE,GAAG,OAAO,CAEzE;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAoBxD;AAED,2DAA2D;AAC3D,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAIlE"}
|
package/dist/flow-common.js
CHANGED
|
@@ -105,6 +105,8 @@ export const FLOW_FAILURE_CLASSES = [
|
|
|
105
105
|
"stalled",
|
|
106
106
|
"config_invalid",
|
|
107
107
|
"internal",
|
|
108
|
+
"review_verdict_missing",
|
|
109
|
+
"verification_unavailable",
|
|
108
110
|
];
|
|
109
111
|
export const FlowFailureClassSchema = Type.Union([
|
|
110
112
|
Type.Literal("provider_error"),
|
|
@@ -120,6 +122,8 @@ export const FlowFailureClassSchema = Type.Union([
|
|
|
120
122
|
Type.Literal("stalled"),
|
|
121
123
|
Type.Literal("config_invalid"),
|
|
122
124
|
Type.Literal("internal"),
|
|
125
|
+
Type.Literal("review_verdict_missing"),
|
|
126
|
+
Type.Literal("verification_unavailable"),
|
|
123
127
|
]);
|
|
124
128
|
export const FlowReasonClassSchema = Type.Union([FlowFailureClassSchema, Type.Literal("size_underestimated")]);
|
|
125
129
|
export const FlowProfileRefSchema = StrictObject({
|
package/dist/flow-common.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"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AAmB,CAAC,CAAC;QAC9E,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IAC/E,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,MAAM,IAAI,iBAAiB,CAAC,mBAAmB,CAAC,CAAC;IAChF,MAAM,MAAM,GAAG,KAAgC,CAAC;IAChD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC9C,IAAI,CAAC,GAAG,CAAC,YAAY,EAAE;YAAE,MAAM,IAAI,iBAAiB,CAAC,mBAAmB,CAAC,CAAC;QAC1E,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS;YAAE,SAAS;QACxC,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,iBAAiB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;AAC/B,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,gBAAgB,CAAC,GAAW,EAAE,IAAY;IACzD,MAAM,IAAI,GAA4B,EAAE,GAAG,GAAG,EAAE,CAAC;IACjD,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { type Static, type TLiteral, type TSchema, type TUnion, Type } from \"typebox\";\nimport { Compile } from \"typebox/compile\";\n\n/**\n * Shared primitives for the `./flow-*` contract subpaths. TypeBox-only and browser-safe: no node:* imports,\n * no hashing (callers inject `sha256Hex`), no free-text string types.\n */\n\nexport const FLOW_ID_PATTERN = \"^[a-z0-9][a-z0-9_.:-]{0,127}$\";\n/** Model ids may be provider-qualified: lowercase, at most one `/`, no empty segment, <= 128 chars in total. */\nexport const FLOW_MODEL_ID_PATTERN = \"^(?=.{1,128}$)[a-z0-9][a-z0-9_.:-]*(?:/[a-z0-9][a-z0-9_.:-]*)?$\";\nexport const FLOW_DIGEST_PATTERN = \"^[a-f0-9]{64}$\";\nconst FLOW_TS_PATTERN =\n\t\"^\\\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\\\d|3[01])T(?:[01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d(?:\\\\.\\\\d{1,9})?(?:Z|[+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)$\";\n\nexport const FLOW_CONTRACT_ERROR_CODES = {\n\tprofile_invalid: \"Invalid flow profile\",\n\tadmission_invalid: \"Invalid flow run admission\",\n\tevent_invalid: \"Invalid flow event\",\n\tcommand_invalid: \"Invalid flow control command\",\n\treceipt_invalid: \"Invalid flow control receipt\",\n\tstatus_invalid: \"Invalid flow status\",\n\tdigest_mismatch: \"Flow digest mismatch\",\n\tdigest_unverifiable: \"Flow digest cannot be verified\",\n\tcanonical_invalid: \"Flow data cannot be canonicalized\",\n\treceipt_conflict: \"Flow receipt conflicts with the first receipt\",\n} as const;\nexport type FlowContractErrorCode = keyof typeof FLOW_CONTRACT_ERROR_CODES;\n\n/** Messages are constants chosen by contract code from `code`; rejected input is never echoed. */\nexport class FlowContractError extends Error {\n\treadonly code: FlowContractErrorCode;\n\tconstructor(code: FlowContractErrorCode) {\n\t\tsuper(FLOW_CONTRACT_ERROR_CODES[code]);\n\t\tthis.name = \"FlowContractError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Union of string literals with a precise Static type (a mapped array would infer `never`). */\nexport const lit = <const T extends readonly string[]>(...values: T) =>\n\tType.Union(values.map((value) => Type.Literal(value))) as unknown as TUnion<{\n\t\t-readonly [K in keyof T]: TLiteral<T[K]>;\n\t}>;\n\nexport const StrictObject = <const T extends Parameters<typeof Type.Object>[0]>(properties: T) =>\n\tType.Object(properties, { additionalProperties: false });\n\nexport const FlowIdSchema = Type.String({ pattern: FLOW_ID_PATTERN });\nexport const FlowDigestSchema = Type.String({ pattern: FLOW_DIGEST_PATTERN });\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;\n\n/** Pattern-valid timestamps only: rejects impossible calendar dates such as 2026-02-31 or a non-leap Feb 29. */\nfunction isRealCalendarDate(timestamp: string): boolean {\n\tconst year = Number(timestamp.slice(0, 4));\n\tconst month = Number(timestamp.slice(5, 7));\n\tconst day = Number(timestamp.slice(8, 10));\n\tconst leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\treturn day <= (month === 2 && leap ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0));\n}\n\nexport const FlowTimestampSchema = Type.Refine(Type.String({ pattern: FLOW_TS_PATTERN }), isRealCalendarDate);\nexport const FlowMicrousdSchema = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });\nexport const FlowCountSchema = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });\nexport const FlowPositiveIntSchema = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });\n\nexport const FlowModelRefSchema = StrictObject({\n\tprovider: FlowIdSchema,\n\tmodel: Type.String({ pattern: FLOW_MODEL_ID_PATTERN }),\n});\nexport type FlowModelRef = Static<typeof FlowModelRefSchema>;\n\nexport const FLOW_ROLES = [\n\t\"scout\",\n\t\"worker\",\n\t\"implementer\",\n\t\"lead\",\n\t\"lead_large\",\n\t\"architect\",\n\t\"reviewer\",\n\t\"security_reviewer\",\n\t\"qa\",\n\t\"triage\",\n] as const;\nexport type FlowRole = (typeof FLOW_ROLES)[number];\nexport const FlowRoleSchema = Type.Union([\n\tType.Literal(\"scout\"),\n\tType.Literal(\"worker\"),\n\tType.Literal(\"implementer\"),\n\tType.Literal(\"lead\"),\n\tType.Literal(\"lead_large\"),\n\tType.Literal(\"architect\"),\n\tType.Literal(\"reviewer\"),\n\tType.Literal(\"security_reviewer\"),\n\tType.Literal(\"qa\"),\n\tType.Literal(\"triage\"),\n]);\n\n/** `Partial<Record<FlowRole, T>>` as a strict object. */\nexport const partialByRole = <T extends TSchema>(schema: T) =>\n\tStrictObject({\n\t\tscout: Type.Optional(schema),\n\t\tworker: Type.Optional(schema),\n\t\timplementer: Type.Optional(schema),\n\t\tlead: Type.Optional(schema),\n\t\tlead_large: Type.Optional(schema),\n\t\tarchitect: Type.Optional(schema),\n\t\treviewer: Type.Optional(schema),\n\t\tsecurity_reviewer: Type.Optional(schema),\n\t\tqa: Type.Optional(schema),\n\t\ttriage: Type.Optional(schema),\n\t});\n\nexport const FLOW_SIZES = [\"small\", \"medium\", \"large\"] as const;\nexport type FlowSize = (typeof FLOW_SIZES)[number];\nexport const FlowSizeSchema = Type.Union([Type.Literal(\"small\"), Type.Literal(\"medium\"), Type.Literal(\"large\")]);\n\nexport const FLOW_FAILURE_CLASSES = [\n\t\"provider_error\",\n\t\"rate_limit\",\n\t\"timeout\",\n\t\"check_failed\",\n\t\"review_rejected\",\n\t\"qa_failed\",\n\t\"budget_stop\",\n\t\"cancelled\",\n\t\"crash\",\n\t\"unsafe_scope\",\n\t\"stalled\",\n\t\"config_invalid\",\n\t\"internal\",\n] as const;\nexport type FlowFailureClass = (typeof FLOW_FAILURE_CLASSES)[number];\nexport const FlowFailureClassSchema = Type.Union([\n\tType.Literal(\"provider_error\"),\n\tType.Literal(\"rate_limit\"),\n\tType.Literal(\"timeout\"),\n\tType.Literal(\"check_failed\"),\n\tType.Literal(\"review_rejected\"),\n\tType.Literal(\"qa_failed\"),\n\tType.Literal(\"budget_stop\"),\n\tType.Literal(\"cancelled\"),\n\tType.Literal(\"crash\"),\n\tType.Literal(\"unsafe_scope\"),\n\tType.Literal(\"stalled\"),\n\tType.Literal(\"config_invalid\"),\n\tType.Literal(\"internal\"),\n]);\n\nexport const FlowReasonClassSchema = Type.Union([FlowFailureClassSchema, Type.Literal(\"size_underestimated\")]);\nexport type FlowReasonClass = Static<typeof FlowReasonClassSchema>;\n\nexport const FlowProfileRefSchema = StrictObject({\n\tid: FlowIdSchema,\n\tversion: FlowPositiveIntSchema,\n\tdigest: FlowDigestSchema,\n});\nexport type FlowProfileRefV1 = Static<typeof FlowProfileRefSchema>;\n\n/** Hasher injected by the host; keeps contracts free of node:crypto. Required by every digest-verifying parser. */\nexport type FlowDigestHasher = { sha256Hex: (text: string) => string };\n\n/** True when `sha256Hex(text)` equals `expected`. A missing, throwing or non-string hasher is a constant error. */\nexport function verifyFlowDigest(hasher: FlowDigestHasher, text: string, expected: string): boolean {\n\tlet actual: unknown;\n\ttry {\n\t\tactual = hasher.sha256Hex(text);\n\t} catch {\n\t\tthrow new FlowContractError(\"digest_unverifiable\");\n\t}\n\tif (typeof actual !== \"string\") throw new FlowContractError(\"digest_unverifiable\");\n\treturn actual === expected;\n}\n\nconst MAX_SNAPSHOT_DEPTH = 16;\nconst MAX_SNAPSHOT_NODES = 10_000;\nconst MAX_SNAPSHOT_STRING = 65_536;\n\nfunction isIndexKey(key: string, length: number): boolean {\n\tconst index = Number(key);\n\treturn Number.isInteger(index) && index >= 0 && index < length && String(index) === key;\n}\n\nfunction snapshotValue(value: unknown, depth: number, budget: { nodes: number }): unknown {\n\tbudget.nodes += 1;\n\tif (depth > MAX_SNAPSHOT_DEPTH || budget.nodes > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\tif (value === null || typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tif (value.length > MAX_SNAPSHOT_STRING || !value.isWellFormed()) throw new Error(\"string\");\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new Error(\"number\");\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") throw new Error(\"type\");\n\tif (Array.isArray(value)) {\n\t\tconst length = value.length;\n\t\tif (length > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (typeof key !== \"string\" || (key !== \"length\" && !isIndexKey(key, length))) throw new Error(\"array\");\n\t\t}\n\t\tconst out: unknown[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\tif (descriptor === undefined || !(\"value\" in descriptor)) throw new Error(\"array\");\n\t\t\tout.push(snapshotValue(descriptor.value, depth + 1, budget));\n\t\t}\n\t\treturn out;\n\t}\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== null && Object.getPrototypeOf(proto) !== null) throw new Error(\"prototype\");\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tif (typeof key !== \"string\" || !key.isWellFormed()) throw new Error(\"key\");\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor === undefined || !(\"value\" in descriptor) || descriptor.enumerable !== true)\n\t\t\tthrow new Error(\"property\");\n\t\tif (descriptor.value === undefined) continue; // JSON semantics: an undefined property is absent\n\t\tObject.defineProperty(out, key, {\n\t\t\tvalue: snapshotValue(descriptor.value, depth + 1, budget),\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn out;\n}\n\n/**\n * Plain-data snapshot of untrusted input: own enumerable data properties only (accessors, symbols, exotic and\n * non-plain objects are rejected), bounded depth/size, finite numbers, well-formed strings. Each property is read\n * exactly once, so the snapshot cannot change after it has been validated.\n */\nexport function snapshotFlowData(input: unknown): unknown {\n\treturn snapshotValue(input, 0, { nodes: 0 });\n}\n\n/**\n * Snapshot `input`, validate the snapshot, return the snapshot. Anything thrown while inspecting hostile input\n * (getters, proxy traps, forged FlowContractError objects) is discarded and replaced by a NEW constant `code` error;\n * the thrown value is never read, compared or rethrown. Only our own validation, after the snapshot exists, may throw.\n */\nexport function parseFlowData<T>(\n\tcode: FlowContractErrorCode,\n\tinput: unknown,\n\tvalidate: (snapshot: unknown) => snapshot is T,\n): T {\n\tconst snapshot = trySnapshotFlowData(code, input);\n\tif (!validate(snapshot)) throw new FlowContractError(code);\n\treturn snapshot;\n}\n\n/** `snapshotFlowData` whose every failure is a new `FlowContractError(code)`; the thrown value is not inspected. */\nexport function trySnapshotFlowData(code: FlowContractErrorCode, input: unknown): unknown {\n\ttry {\n\t\treturn snapshotFlowData(input);\n\t} catch {\n\t\tthrow new FlowContractError(code);\n\t}\n}\n\nexport function compileFlow<T extends TSchema>(schema: T) {\n\treturn Compile(schema);\n}\n\nexport function modelKey(ref: FlowModelRef): string {\n\treturn `${ref.provider}\\u0000${ref.model}`;\n}\n\nexport function hasDuplicateModels(refs: readonly FlowModelRef[]): boolean {\n\treturn new Set(refs.map(modelKey)).size !== refs.length;\n}\n\n/**\n * Canonical JSON text (RFC 8785 JCS subset): object keys sorted by UTF-16 code unit, no whitespace, `undefined`\n * properties omitted, numbers as ECMAScript Number toString (`JSON.stringify`; -0 prints 0, 1e21 prints 1e+21).\n * Lone surrogates (keys or strings), non-finite numbers and non-JSON values are rejected with a constant error.\n */\nexport function canonicalFlowJson(value: unknown): string {\n\tif (value === null || typeof value === \"boolean\") return JSON.stringify(value);\n\tif (typeof value === \"string\") {\n\t\tif (!value.isWellFormed()) throw new FlowContractError(\"canonical_invalid\");\n\t\treturn JSON.stringify(value);\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new FlowContractError(\"canonical_invalid\");\n\t\treturn JSON.stringify(value);\n\t}\n\tif (Array.isArray(value)) return `[${value.map(canonicalFlowJson).join(\",\")}]`;\n\tif (typeof value !== \"object\") throw new FlowContractError(\"canonical_invalid\");\n\tconst record = value as Record<string, unknown>;\n\tconst parts: string[] = [];\n\tfor (const key of Object.keys(record).sort()) {\n\t\tif (!key.isWellFormed()) throw new FlowContractError(\"canonical_invalid\");\n\t\tif (record[key] === undefined) continue;\n\t\tparts.push(`${JSON.stringify(key)}:${canonicalFlowJson(record[key])}`);\n\t}\n\treturn `{${parts.join(\",\")}}`;\n}\n\n/** Canonical text of `doc` without the property `omit`. */\nexport function canonicalWithout(doc: object, omit: string): string {\n\tconst copy: Record<string, unknown> = { ...doc };\n\tdelete copy[omit];\n\treturn canonicalFlowJson(copy);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flow-common.js","sourceRoot":"","sources":["../src/flow-common.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyD,IAAI,EAAE,MAAM,SAAS,CAAC;AACtF,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAE1C;;;GAGG;AAEH,MAAM,CAAC,MAAM,eAAe,GAAG,+BAA+B,CAAC;AAC/D,gHAAgH;AAChH,MAAM,CAAC,MAAM,qBAAqB,GAAG,iEAAiE,CAAC;AACvG,MAAM,CAAC,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AACpD,MAAM,eAAe,GACpB,+IAA+I,CAAC;AAEjJ,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,eAAe,EAAE,sBAAsB;IACvC,iBAAiB,EAAE,4BAA4B;IAC/C,aAAa,EAAE,oBAAoB;IACnC,eAAe,EAAE,8BAA8B;IAC/C,eAAe,EAAE,8BAA8B;IAC/C,cAAc,EAAE,qBAAqB;IACrC,eAAe,EAAE,sBAAsB;IACvC,mBAAmB,EAAE,gCAAgC;IACrD,iBAAiB,EAAE,mCAAmC;IACtD,gBAAgB,EAAE,+CAA+C;CACxD,CAAC;AAGX,kGAAkG;AAClG,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAClC,IAAI,CAAwB;IACrC,YAAY,IAA2B;QACtC,KAAK,CAAC,yBAAyB,CAAC,IAAI,CAAC,CAAC,CAAC;QACvC,IAAI,CAAC,IAAI,GAAG,mBAAm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,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;AAC/B,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,gBAAgB,CAAC,GAAW,EAAE,IAAY;IACzD,MAAM,IAAI,GAA4B,EAAE,GAAG,GAAG,EAAE,CAAC;IACjD,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import { type Static, type TLiteral, type TSchema, type TUnion, Type } from \"typebox\";\nimport { Compile } from \"typebox/compile\";\n\n/**\n * Shared primitives for the `./flow-*` contract subpaths. TypeBox-only and browser-safe: no node:* imports,\n * no hashing (callers inject `sha256Hex`), no free-text string types.\n */\n\nexport const FLOW_ID_PATTERN = \"^[a-z0-9][a-z0-9_.:-]{0,127}$\";\n/** Model ids may be provider-qualified: lowercase, at most one `/`, no empty segment, <= 128 chars in total. */\nexport const FLOW_MODEL_ID_PATTERN = \"^(?=.{1,128}$)[a-z0-9][a-z0-9_.:-]*(?:/[a-z0-9][a-z0-9_.:-]*)?$\";\nexport const FLOW_DIGEST_PATTERN = \"^[a-f0-9]{64}$\";\nconst FLOW_TS_PATTERN =\n\t\"^\\\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\\\d|3[01])T(?:[01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d(?:\\\\.\\\\d{1,9})?(?:Z|[+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)$\";\n\nexport const FLOW_CONTRACT_ERROR_CODES = {\n\tprofile_invalid: \"Invalid flow profile\",\n\tadmission_invalid: \"Invalid flow run admission\",\n\tevent_invalid: \"Invalid flow event\",\n\tcommand_invalid: \"Invalid flow control command\",\n\treceipt_invalid: \"Invalid flow control receipt\",\n\tstatus_invalid: \"Invalid flow status\",\n\tdigest_mismatch: \"Flow digest mismatch\",\n\tdigest_unverifiable: \"Flow digest cannot be verified\",\n\tcanonical_invalid: \"Flow data cannot be canonicalized\",\n\treceipt_conflict: \"Flow receipt conflicts with the first receipt\",\n} as const;\nexport type FlowContractErrorCode = keyof typeof FLOW_CONTRACT_ERROR_CODES;\n\n/** Messages are constants chosen by contract code from `code`; rejected input is never echoed. */\nexport class FlowContractError extends Error {\n\treadonly code: FlowContractErrorCode;\n\tconstructor(code: FlowContractErrorCode) {\n\t\tsuper(FLOW_CONTRACT_ERROR_CODES[code]);\n\t\tthis.name = \"FlowContractError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Union of string literals with a precise Static type (a mapped array would infer `never`). */\nexport const lit = <const T extends readonly string[]>(...values: T) =>\n\tType.Union(values.map((value) => Type.Literal(value))) as unknown as TUnion<{\n\t\t-readonly [K in keyof T]: TLiteral<T[K]>;\n\t}>;\n\nexport const StrictObject = <const T extends Parameters<typeof Type.Object>[0]>(properties: T) =>\n\tType.Object(properties, { additionalProperties: false });\n\nexport const FlowIdSchema = Type.String({ pattern: FLOW_ID_PATTERN });\nexport const FlowDigestSchema = Type.String({ pattern: FLOW_DIGEST_PATTERN });\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;\n\n/** Pattern-valid timestamps only: rejects impossible calendar dates such as 2026-02-31 or a non-leap Feb 29. */\nfunction isRealCalendarDate(timestamp: string): boolean {\n\tconst year = Number(timestamp.slice(0, 4));\n\tconst month = Number(timestamp.slice(5, 7));\n\tconst day = Number(timestamp.slice(8, 10));\n\tconst leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\treturn day <= (month === 2 && leap ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0));\n}\n\nexport const FlowTimestampSchema = Type.Refine(Type.String({ pattern: FLOW_TS_PATTERN }), isRealCalendarDate);\nexport const FlowMicrousdSchema = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });\nexport const FlowCountSchema = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });\nexport const FlowPositiveIntSchema = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });\n\nexport const FlowModelRefSchema = StrictObject({\n\tprovider: FlowIdSchema,\n\tmodel: Type.String({ pattern: FLOW_MODEL_ID_PATTERN }),\n});\nexport type FlowModelRef = Static<typeof FlowModelRefSchema>;\n\nexport const FLOW_ROLES = [\n\t\"scout\",\n\t\"worker\",\n\t\"implementer\",\n\t\"lead\",\n\t\"lead_large\",\n\t\"architect\",\n\t\"reviewer\",\n\t\"security_reviewer\",\n\t\"qa\",\n\t\"triage\",\n] as const;\nexport type FlowRole = (typeof FLOW_ROLES)[number];\nexport const FlowRoleSchema = Type.Union([\n\tType.Literal(\"scout\"),\n\tType.Literal(\"worker\"),\n\tType.Literal(\"implementer\"),\n\tType.Literal(\"lead\"),\n\tType.Literal(\"lead_large\"),\n\tType.Literal(\"architect\"),\n\tType.Literal(\"reviewer\"),\n\tType.Literal(\"security_reviewer\"),\n\tType.Literal(\"qa\"),\n\tType.Literal(\"triage\"),\n]);\n\n/** `Partial<Record<FlowRole, T>>` as a strict object. */\nexport const partialByRole = <T extends TSchema>(schema: T) =>\n\tStrictObject({\n\t\tscout: Type.Optional(schema),\n\t\tworker: Type.Optional(schema),\n\t\timplementer: Type.Optional(schema),\n\t\tlead: Type.Optional(schema),\n\t\tlead_large: Type.Optional(schema),\n\t\tarchitect: Type.Optional(schema),\n\t\treviewer: Type.Optional(schema),\n\t\tsecurity_reviewer: Type.Optional(schema),\n\t\tqa: Type.Optional(schema),\n\t\ttriage: Type.Optional(schema),\n\t});\n\nexport const FLOW_SIZES = [\"small\", \"medium\", \"large\"] as const;\nexport type FlowSize = (typeof FLOW_SIZES)[number];\nexport const FlowSizeSchema = Type.Union([Type.Literal(\"small\"), Type.Literal(\"medium\"), Type.Literal(\"large\")]);\n\nexport const FLOW_FAILURE_CLASSES = [\n\t\"provider_error\",\n\t\"rate_limit\",\n\t\"timeout\",\n\t\"check_failed\",\n\t\"review_rejected\",\n\t\"qa_failed\",\n\t\"budget_stop\",\n\t\"cancelled\",\n\t\"crash\",\n\t\"unsafe_scope\",\n\t\"stalled\",\n\t\"config_invalid\",\n\t\"internal\",\n\t\"review_verdict_missing\",\n\t\"verification_unavailable\",\n] as const;\nexport type FlowFailureClass = (typeof FLOW_FAILURE_CLASSES)[number];\nexport const FlowFailureClassSchema = Type.Union([\n\tType.Literal(\"provider_error\"),\n\tType.Literal(\"rate_limit\"),\n\tType.Literal(\"timeout\"),\n\tType.Literal(\"check_failed\"),\n\tType.Literal(\"review_rejected\"),\n\tType.Literal(\"qa_failed\"),\n\tType.Literal(\"budget_stop\"),\n\tType.Literal(\"cancelled\"),\n\tType.Literal(\"crash\"),\n\tType.Literal(\"unsafe_scope\"),\n\tType.Literal(\"stalled\"),\n\tType.Literal(\"config_invalid\"),\n\tType.Literal(\"internal\"),\n\tType.Literal(\"review_verdict_missing\"),\n\tType.Literal(\"verification_unavailable\"),\n]);\n\nexport const FlowReasonClassSchema = Type.Union([FlowFailureClassSchema, Type.Literal(\"size_underestimated\")]);\nexport type FlowReasonClass = Static<typeof FlowReasonClassSchema>;\n\nexport const FlowProfileRefSchema = StrictObject({\n\tid: FlowIdSchema,\n\tversion: FlowPositiveIntSchema,\n\tdigest: FlowDigestSchema,\n});\nexport type FlowProfileRefV1 = Static<typeof FlowProfileRefSchema>;\n\n/** Hasher injected by the host; keeps contracts free of node:crypto. Required by every digest-verifying parser. */\nexport type FlowDigestHasher = { sha256Hex: (text: string) => string };\n\n/** True when `sha256Hex(text)` equals `expected`. A missing, throwing or non-string hasher is a constant error. */\nexport function verifyFlowDigest(hasher: FlowDigestHasher, text: string, expected: string): boolean {\n\tlet actual: unknown;\n\ttry {\n\t\tactual = hasher.sha256Hex(text);\n\t} catch {\n\t\tthrow new FlowContractError(\"digest_unverifiable\");\n\t}\n\tif (typeof actual !== \"string\") throw new FlowContractError(\"digest_unverifiable\");\n\treturn actual === expected;\n}\n\nconst MAX_SNAPSHOT_DEPTH = 16;\nconst MAX_SNAPSHOT_NODES = 10_000;\nconst MAX_SNAPSHOT_STRING = 65_536;\n\nfunction isIndexKey(key: string, length: number): boolean {\n\tconst index = Number(key);\n\treturn Number.isInteger(index) && index >= 0 && index < length && String(index) === key;\n}\n\nfunction snapshotValue(value: unknown, depth: number, budget: { nodes: number }): unknown {\n\tbudget.nodes += 1;\n\tif (depth > MAX_SNAPSHOT_DEPTH || budget.nodes > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\tif (value === null || typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tif (value.length > MAX_SNAPSHOT_STRING || !value.isWellFormed()) throw new Error(\"string\");\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new Error(\"number\");\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") throw new Error(\"type\");\n\tif (Array.isArray(value)) {\n\t\tconst length = value.length;\n\t\tif (length > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (typeof key !== \"string\" || (key !== \"length\" && !isIndexKey(key, length))) throw new Error(\"array\");\n\t\t}\n\t\tconst out: unknown[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\tif (descriptor === undefined || !(\"value\" in descriptor)) throw new Error(\"array\");\n\t\t\tout.push(snapshotValue(descriptor.value, depth + 1, budget));\n\t\t}\n\t\treturn out;\n\t}\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== null && Object.getPrototypeOf(proto) !== null) throw new Error(\"prototype\");\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tif (typeof key !== \"string\" || !key.isWellFormed()) throw new Error(\"key\");\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor === undefined || !(\"value\" in descriptor) || descriptor.enumerable !== true)\n\t\t\tthrow new Error(\"property\");\n\t\tif (descriptor.value === undefined) continue; // JSON semantics: an undefined property is absent\n\t\tObject.defineProperty(out, key, {\n\t\t\tvalue: snapshotValue(descriptor.value, depth + 1, budget),\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn out;\n}\n\n/**\n * Plain-data snapshot of untrusted input: own enumerable data properties only (accessors, symbols, exotic and\n * non-plain objects are rejected), bounded depth/size, finite numbers, well-formed strings. Each property is read\n * exactly once, so the snapshot cannot change after it has been validated.\n */\nexport function snapshotFlowData(input: unknown): unknown {\n\treturn snapshotValue(input, 0, { nodes: 0 });\n}\n\n/**\n * Snapshot `input`, validate the snapshot, return the snapshot. Anything thrown while inspecting hostile input\n * (getters, proxy traps, forged FlowContractError objects) is discarded and replaced by a NEW constant `code` error;\n * the thrown value is never read, compared or rethrown. Only our own validation, after the snapshot exists, may throw.\n */\nexport function parseFlowData<T>(\n\tcode: FlowContractErrorCode,\n\tinput: unknown,\n\tvalidate: (snapshot: unknown) => snapshot is T,\n): T {\n\tconst snapshot = trySnapshotFlowData(code, input);\n\tif (!validate(snapshot)) throw new FlowContractError(code);\n\treturn snapshot;\n}\n\n/** `snapshotFlowData` whose every failure is a new `FlowContractError(code)`; the thrown value is not inspected. */\nexport function trySnapshotFlowData(code: FlowContractErrorCode, input: unknown): unknown {\n\ttry {\n\t\treturn snapshotFlowData(input);\n\t} catch {\n\t\tthrow new FlowContractError(code);\n\t}\n}\n\nexport function compileFlow<T extends TSchema>(schema: T) {\n\treturn Compile(schema);\n}\n\nexport function modelKey(ref: FlowModelRef): string {\n\treturn `${ref.provider}\\u0000${ref.model}`;\n}\n\nexport function hasDuplicateModels(refs: readonly FlowModelRef[]): boolean {\n\treturn new Set(refs.map(modelKey)).size !== refs.length;\n}\n\n/**\n * Canonical JSON text (RFC 8785 JCS subset): object keys sorted by UTF-16 code unit, no whitespace, `undefined`\n * properties omitted, numbers as ECMAScript Number toString (`JSON.stringify`; -0 prints 0, 1e21 prints 1e+21).\n * Lone surrogates (keys or strings), non-finite numbers and non-JSON values are rejected with a constant error.\n */\nexport function canonicalFlowJson(value: unknown): string {\n\tif (value === null || typeof value === \"boolean\") return JSON.stringify(value);\n\tif (typeof value === \"string\") {\n\t\tif (!value.isWellFormed()) throw new FlowContractError(\"canonical_invalid\");\n\t\treturn JSON.stringify(value);\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new FlowContractError(\"canonical_invalid\");\n\t\treturn JSON.stringify(value);\n\t}\n\tif (Array.isArray(value)) return `[${value.map(canonicalFlowJson).join(\",\")}]`;\n\tif (typeof value !== \"object\") throw new FlowContractError(\"canonical_invalid\");\n\tconst record = value as Record<string, unknown>;\n\tconst parts: string[] = [];\n\tfor (const key of Object.keys(record).sort()) {\n\t\tif (!key.isWellFormed()) throw new FlowContractError(\"canonical_invalid\");\n\t\tif (record[key] === undefined) continue;\n\t\tparts.push(`${JSON.stringify(key)}:${canonicalFlowJson(record[key])}`);\n\t}\n\treturn `{${parts.join(\",\")}}`;\n}\n\n/** Canonical text of `doc` without the property `omit`. */\nexport function canonicalWithout(doc: object, omit: string): string {\n\tconst copy: Record<string, unknown> = { ...doc };\n\tdelete copy[omit];\n\treturn canonicalFlowJson(copy);\n}\n"]}
|
package/dist/flow-control.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export declare const FlowControlReceiptV1Schema: Type.TObject<{
|
|
|
34
34
|
readonly id: Type.TString;
|
|
35
35
|
readonly command: Type.TUnion<[Type.TLiteral<"flow_status">, Type.TLiteral<"flow_pause">, Type.TLiteral<"flow_resume">, Type.TLiteral<"flow_cancel">]>;
|
|
36
36
|
readonly state: Type.TUnion<[Type.TLiteral<"accepted">, Type.TLiteral<"applied">, Type.TLiteral<"rejected">]>;
|
|
37
|
-
readonly reason: Type.TOptional<Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">]>, Type.TLiteral<"size_underestimated">]>>;
|
|
37
|
+
readonly reason: Type.TOptional<Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">, Type.TLiteral<"review_verdict_missing">, Type.TLiteral<"verification_unavailable">]>, Type.TLiteral<"size_underestimated">]>>;
|
|
38
38
|
readonly terminationConfirmed: Type.TOptional<Type.TBoolean>;
|
|
39
39
|
}>;
|
|
40
40
|
export type FlowControlReceiptV1 = Static<typeof FlowControlReceiptV1Schema>;
|
|
@@ -45,7 +45,7 @@ export declare const FlowMessageReceiptV1Schema: Type.TObject<{
|
|
|
45
45
|
readonly command: Type.TLiteral<"flow_message">;
|
|
46
46
|
readonly messageId: Type.TString;
|
|
47
47
|
readonly state: Type.TUnion<[Type.TLiteral<"accepted">, Type.TLiteral<"applied">, Type.TLiteral<"rejected">]>;
|
|
48
|
-
readonly reason: Type.TOptional<Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">]>, Type.TLiteral<"size_underestimated">]>>;
|
|
48
|
+
readonly reason: Type.TOptional<Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">, Type.TLiteral<"review_verdict_missing">, Type.TLiteral<"verification_unavailable">]>, Type.TLiteral<"size_underestimated">]>>;
|
|
49
49
|
readonly disposition: Type.TUnion<[Type.TLiteral<"live">, Type.TLiteral<"queued">, Type.TLiteral<"rejected">]>;
|
|
50
50
|
readonly deliveredTo: Type.TOptional<Type.TObject<{
|
|
51
51
|
readonly taskId: Type.TString;
|
|
@@ -69,7 +69,7 @@ export declare const FlowStatusV1Schema: Type.TObject<{
|
|
|
69
69
|
readonly state: Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"running">, Type.TLiteral<"succeeded">, Type.TLiteral<"failed">, Type.TLiteral<"cancelled">]>;
|
|
70
70
|
}>>;
|
|
71
71
|
readonly budgetPct: Type.TNumber;
|
|
72
|
-
readonly warnings: Type.TArray<Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">]>, Type.TLiteral<"size_underestimated">]>>;
|
|
72
|
+
readonly warnings: Type.TArray<Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">, Type.TLiteral<"review_verdict_missing">, Type.TLiteral<"verification_unavailable">]>, Type.TLiteral<"size_underestimated">]>>;
|
|
73
73
|
}>;
|
|
74
74
|
export type FlowStatusV1 = Static<typeof FlowStatusV1Schema>;
|
|
75
75
|
/** Pushed frames (HC -> host). */
|
package/dist/flow-events.d.ts
CHANGED
|
@@ -69,7 +69,7 @@ export declare const FlowEventV1Schema: Type.TUnion<[Type.TObject<{
|
|
|
69
69
|
readonly payload: Type.TObject<{
|
|
70
70
|
readonly from: Type.TUnion<[Type.TLiteral<"small">, Type.TLiteral<"medium">, Type.TLiteral<"large">]>;
|
|
71
71
|
readonly to: Type.TUnion<[Type.TLiteral<"small">, Type.TLiteral<"medium">, Type.TLiteral<"large">]>;
|
|
72
|
-
readonly reasonClass: Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">]>, Type.TLiteral<"size_underestimated">]>;
|
|
72
|
+
readonly reasonClass: Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">, Type.TLiteral<"review_verdict_missing">, Type.TLiteral<"verification_unavailable">]>, Type.TLiteral<"size_underestimated">]>;
|
|
73
73
|
}>;
|
|
74
74
|
}>, Type.TObject<{
|
|
75
75
|
readonly schema: Type.TLiteral<"humain-flow-event">;
|
|
@@ -93,7 +93,7 @@ export declare const FlowEventV1Schema: Type.TUnion<[Type.TObject<{
|
|
|
93
93
|
readonly model: Type.TString;
|
|
94
94
|
}>;
|
|
95
95
|
readonly effort: Type.TUnion<[Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">]>;
|
|
96
|
-
readonly binding: Type.TUnion<[Type.TLiteral<"primary">, Type.TLiteral<"backup">]>;
|
|
96
|
+
readonly binding: Type.TUnion<[Type.TLiteral<"primary">, Type.TLiteral<"backup">, Type.TLiteral<"lead_selected">]>;
|
|
97
97
|
readonly backupIndex: Type.TInteger;
|
|
98
98
|
}>;
|
|
99
99
|
}>, Type.TObject<{
|
|
@@ -121,7 +121,7 @@ export declare const FlowEventV1Schema: Type.TUnion<[Type.TObject<{
|
|
|
121
121
|
readonly provider: Type.TString;
|
|
122
122
|
readonly model: Type.TString;
|
|
123
123
|
}>;
|
|
124
|
-
readonly reasonClass: Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">]>, Type.TLiteral<"size_underestimated">]>;
|
|
124
|
+
readonly reasonClass: Type.TUnion<[Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">, Type.TLiteral<"review_verdict_missing">, Type.TLiteral<"verification_unavailable">]>, Type.TLiteral<"size_underestimated">]>;
|
|
125
125
|
}>;
|
|
126
126
|
}>, Type.TObject<{
|
|
127
127
|
readonly schema: Type.TLiteral<"humain-flow-event">;
|
|
@@ -142,7 +142,7 @@ export declare const FlowEventV1Schema: Type.TUnion<[Type.TObject<{
|
|
|
142
142
|
readonly role: Type.TUnion<[Type.TLiteral<"scout">, Type.TLiteral<"worker">, Type.TLiteral<"implementer">, Type.TLiteral<"lead">, Type.TLiteral<"lead_large">, Type.TLiteral<"architect">, Type.TLiteral<"reviewer">, Type.TLiteral<"security_reviewer">, Type.TLiteral<"qa">, Type.TLiteral<"triage">]>;
|
|
143
143
|
readonly attempt: Type.TInteger;
|
|
144
144
|
readonly state: Type.TUnion<[Type.TLiteral<"started">, Type.TLiteral<"succeeded">, Type.TLiteral<"failed">, Type.TLiteral<"retried">, Type.TLiteral<"cancelled">]>;
|
|
145
|
-
readonly failureClass: Type.TOptional<Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">]>>;
|
|
145
|
+
readonly failureClass: Type.TOptional<Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">, Type.TLiteral<"review_verdict_missing">, Type.TLiteral<"verification_unavailable">]>>;
|
|
146
146
|
}>;
|
|
147
147
|
}>, Type.TObject<{
|
|
148
148
|
readonly schema: Type.TLiteral<"humain-flow-event">;
|
|
@@ -272,7 +272,7 @@ export declare const FlowEventV1Schema: Type.TUnion<[Type.TObject<{
|
|
|
272
272
|
readonly kind: Type.TLiteral<"run_settled">;
|
|
273
273
|
readonly payload: Type.TObject<{
|
|
274
274
|
readonly outcome: Type.TUnion<[Type.TLiteral<"succeeded">, Type.TLiteral<"failed">, Type.TLiteral<"cancelled">, Type.TLiteral<"budget_stopped">, Type.TLiteral<"interrupted">]>;
|
|
275
|
-
readonly failureClass: Type.TOptional<Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">]>>;
|
|
275
|
+
readonly failureClass: Type.TOptional<Type.TUnion<[Type.TLiteral<"provider_error">, Type.TLiteral<"rate_limit">, Type.TLiteral<"timeout">, Type.TLiteral<"check_failed">, Type.TLiteral<"review_rejected">, Type.TLiteral<"qa_failed">, Type.TLiteral<"budget_stop">, Type.TLiteral<"cancelled">, Type.TLiteral<"crash">, Type.TLiteral<"unsafe_scope">, Type.TLiteral<"stalled">, Type.TLiteral<"config_invalid">, Type.TLiteral<"internal">, Type.TLiteral<"review_verdict_missing">, Type.TLiteral<"verification_unavailable">]>>;
|
|
276
276
|
readonly settledCleanly: Type.TBoolean;
|
|
277
277
|
readonly retryOffer: Type.TArray<Type.TUnion<[Type.TLiteral<"flow">, Type.TLiteral<"direct">]>>;
|
|
278
278
|
readonly totals: Type.TObject<{
|
package/dist/flow-events.js
CHANGED
|
@@ -65,7 +65,7 @@ export const FlowEventV1Schema = Type.Union([
|
|
|
65
65
|
role: FlowRoleSchema,
|
|
66
66
|
model: EventModelRefSchema,
|
|
67
67
|
effort: Effort,
|
|
68
|
-
binding: lit("primary", "backup"),
|
|
68
|
+
binding: lit("primary", "backup", "lead_selected"),
|
|
69
69
|
backupIndex: Type.Integer({ minimum: 0, maximum: 7 }),
|
|
70
70
|
})),
|
|
71
71
|
event("fallback", StrictObject({
|
package/dist/flow-events.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow-events.js","sourceRoot":"","sources":["../src/flow-events.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,IAAI,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EACN,WAAW,EACX,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACrB,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,GAAG,EACH,aAAa,EACb,aAAa,EACb,YAAY,GACZ,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,oBAAoB,EAAyB,MAAM,kBAAkB,CAAC;AAE/E;;;;;GAKG;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC/B,aAAa;IACb,cAAc;IACd,WAAW;IACX,aAAa;IACb,UAAU;IACV,SAAS;IACT,eAAe;IACf,SAAS;IACT,QAAQ;IACR,SAAS;IACT,SAAS;IACT,aAAa;CACJ,CAAC;AAGX,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AACnC,MAAM,MAAM,GAAG,GAAG,CAAC,KAA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CAAC;AAED,SAAS,OAAO,CAAC,KAAc;IAC9B,OAAO,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC9C,OAAO,aAAa,CAAC,eAAe,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import { type Static, type TSchema, Type } from \"typebox\";\nimport {\n\tcompileFlow,\n\tFLOW_ID_PATTERN,\n\tFlowCountSchema,\n\tFlowDigestSchema,\n\tFlowFailureClassSchema,\n\tFlowIdSchema,\n\tFlowMicrousdSchema,\n\tFlowPositiveIntSchema,\n\tFlowProfileRefSchema,\n\tFlowReasonClassSchema,\n\tFlowRoleSchema,\n\tFlowSizeSchema,\n\tFlowTimestampSchema,\n\tlit,\n\tparseFlowData,\n\tpartialByRole,\n\tStrictObject,\n} from \"./flow-common.ts\";\n\nexport { FlowProfileRefSchema, type FlowProfileRefV1 } from \"./flow-common.ts\";\n\n/**\n * Privacy rule: every string in an event is an Id, a Digest, an enum literal, or an ISO timestamp.\n * There is no free-text field, so prompts, messages and model output have no place to go. Syntax checks cannot tell\n * semantic content, though: a path-like string can match an Id or model pattern. Producers must put only catalog\n * provider/model identifiers in those fields (see docs/flow-contracts.md, trust boundaries).\n */\n\nexport const FLOW_EVENT_KINDS = [\n\t\"run_started\",\n\t\"size_decided\",\n\t\"escalated\",\n\t\"route_bound\",\n\t\"fallback\",\n\t\"attempt\",\n\t\"request_usage\",\n\t\"verdict\",\n\t\"budget\",\n\t\"control\",\n\t\"message\",\n\t\"run_settled\",\n] as const;\nexport type FlowEventKind = (typeof FLOW_EVENT_KINDS)[number];\n\nconst Mode = lit(\"auto\", \"direct\");\nconst Effort = lit(\"low\", \"medium\", \"high\");\nconst EventModelRefSchema = StrictObject({ provider: FlowIdSchema, model: Type.String({ pattern: FLOW_ID_PATTERN }) });\n\nconst event = <const K extends string, P extends TSchema>(kind: K, payload: P) =>\n\tStrictObject({\n\t\tschema: Type.Literal(\"humain-flow-event\"),\n\t\tschemaVersion: Type.Literal(1),\n\t\teventId: FlowIdSchema,\n\t\trunId: FlowIdSchema,\n\t\tseq: FlowPositiveIntSchema,\n\t\tts: FlowTimestampSchema,\n\t\tprofile: FlowProfileRefSchema,\n\t\tcauses: Type.Array(FlowIdSchema, { maxItems: 16 }),\n\t\tkind: Type.Literal(kind),\n\t\tpayload,\n\t});\n\nconst RoleTotals = StrictObject({\n\ttokens: FlowCountSchema,\n\tcostMicrousd: FlowMicrousdSchema,\n\tdurationMs: FlowCountSchema,\n\trequests: FlowCountSchema,\n});\n\nexport const FlowEventV1Schema = Type.Union([\n\tevent(\n\t\t\"run_started\",\n\t\tStrictObject({\n\t\t\tmode: Mode,\n\t\t\tsurface: lit(\"cli\", \"web\"),\n\t\t\tadmissionDigest: FlowDigestSchema,\n\t\t\tinputsCount: FlowCountSchema,\n\t\t\tgoalSha256: FlowDigestSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"size_decided\",\n\t\tStrictObject({\n\t\t\tsize: FlowSizeSchema,\n\t\t\tsource: lit(\"rules\", \"triage\", \"override\"),\n\t\t\truleScore: Type.Number({ minimum: 0, maximum: 1_000_000 }),\n\t\t\tthresholds: StrictObject({\n\t\t\t\tmediumAt: Type.Number({ minimum: 0, maximum: 1_000_000 }),\n\t\t\t\tlargeAt: Type.Number({ minimum: 0, maximum: 1_000_000 }),\n\t\t\t}),\n\t\t}),\n\t),\n\tevent(\"escalated\", StrictObject({ from: FlowSizeSchema, to: FlowSizeSchema, reasonClass: FlowReasonClassSchema })),\n\tevent(\n\t\t\"route_bound\",\n\t\tStrictObject({\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tmodel: EventModelRefSchema,\n\t\t\teffort: Effort,\n\t\t\tbinding: lit(\"primary\", \"backup\"),\n\t\t\tbackupIndex: Type.Integer({ minimum: 0, maximum: 7 }),\n\t\t}),\n\t),\n\tevent(\n\t\t\"fallback\",\n\t\tStrictObject({\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tfrom: EventModelRefSchema,\n\t\t\tto: EventModelRefSchema,\n\t\t\treasonClass: FlowReasonClassSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"attempt\",\n\t\tStrictObject({\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tattempt: FlowPositiveIntSchema,\n\t\t\tstate: lit(\"started\", \"succeeded\", \"failed\", \"retried\", \"cancelled\"),\n\t\t\tfailureClass: Type.Optional(FlowFailureClassSchema),\n\t\t}),\n\t),\n\tevent(\n\t\t\"request_usage\",\n\t\tStrictObject({\n\t\t\trequestId: FlowIdSchema,\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tmodel: EventModelRefSchema,\n\t\t\tinputTokens: FlowCountSchema,\n\t\t\toutputTokens: FlowCountSchema,\n\t\t\tcacheReadTokens: FlowCountSchema,\n\t\t\tcacheWriteTokens: FlowCountSchema,\n\t\t\tcostMicrousd: Type.Union([FlowMicrousdSchema, Type.Null()]),\n\t\t\tcostBasis: lit(\"reported\", \"estimated\", \"unknown\"),\n\t\t\tdurationMs: FlowCountSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"verdict\",\n\t\tStrictObject({\n\t\t\tstage: lit(\"check\", \"review\", \"qa\"),\n\t\t\ttaskId: FlowIdSchema,\n\t\t\tverdict: lit(\"pass\", \"fail\", \"blocked\"),\n\t\t\tfindingsCount: FlowCountSchema,\n\t\t\tcheckId: Type.Optional(FlowIdSchema),\n\t\t}),\n\t),\n\tevent(\n\t\t\"budget\",\n\t\tStrictObject({\n\t\t\tspentMicrousd: FlowMicrousdSchema,\n\t\t\tcapMicrousd: FlowMicrousdSchema,\n\t\t\tpct: Type.Number({ minimum: 0, maximum: 100 }),\n\t\t\tstate: lit(\"ok\", \"warn\", \"stop\"),\n\t\t}),\n\t),\n\tevent(\n\t\t\"control\",\n\t\tStrictObject({\n\t\t\taction: lit(\"pause\", \"resume\", \"cancel\", \"message\", \"status\"),\n\t\t\tcommandId: FlowIdSchema,\n\t\t\tstate: lit(\"accepted\", \"applied\", \"rejected\"),\n\t\t\tlatencyMs: FlowCountSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"message\",\n\t\tStrictObject({\n\t\t\tmessageId: FlowIdSchema,\n\t\t\tdisposition: lit(\"live\", \"queued\", \"rejected\"),\n\t\t\ttargetRole: FlowRoleSchema,\n\t\t\ttextSha256: FlowDigestSchema,\n\t\t\ttextLength: Type.Integer({ minimum: 1, maximum: 16_000 }),\n\t\t}),\n\t),\n\tevent(\n\t\t\"run_settled\",\n\t\tStrictObject({\n\t\t\toutcome: lit(\"succeeded\", \"failed\", \"cancelled\", \"budget_stopped\", \"interrupted\"),\n\t\t\tfailureClass: Type.Optional(FlowFailureClassSchema),\n\t\t\tsettledCleanly: Type.Boolean(),\n\t\t\t// Subset of the two retry modes offered to the user; unique, order-free (full offer = both).\n\t\t\tretryOffer: Type.Array(lit(\"flow\", \"direct\"), { maxItems: 2, uniqueItems: true }),\n\t\t\ttotals: partialByRole(RoleTotals),\n\t\t}),\n\t),\n]);\nexport type FlowEventV1 = Static<typeof FlowEventV1Schema>;\n\nconst Validator = compileFlow(FlowEventV1Schema);\n\n/** `request_usage.costMicrousd` is null exactly when `costBasis` is \"unknown\"; never 0 for unknown. */\nfunction crossFieldsValid(doc: FlowEventV1): boolean {\n\tif (doc.kind === \"request_usage\")\n\t\treturn (doc.payload.costMicrousd === null) === (doc.payload.costBasis === \"unknown\");\n\treturn true;\n}\n\nfunction isEvent(value: unknown): value is FlowEventV1 {\n\treturn Validator.Check(value) && crossFieldsValid(value);\n}\n\n/** Validates a plain-data snapshot of `input` and returns the snapshot (never the caller's object). */\nexport function parseFlowEventV1(input: unknown): FlowEventV1 {\n\treturn parseFlowData(\"event_invalid\", input, isEvent);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flow-events.js","sourceRoot":"","sources":["../src/flow-events.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,IAAI,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EACN,WAAW,EACX,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACrB,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,GAAG,EACH,aAAa,EACb,aAAa,EACb,YAAY,GACZ,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,oBAAoB,EAAyB,MAAM,kBAAkB,CAAC;AAE/E;;;;;GAKG;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC/B,aAAa;IACb,cAAc;IACd,WAAW;IACX,aAAa;IACb,UAAU;IACV,SAAS;IACT,eAAe;IACf,SAAS;IACT,QAAQ;IACR,SAAS;IACT,SAAS;IACT,aAAa;CACJ,CAAC;AAGX,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AACnC,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC5C,MAAM,mBAAmB,GAAG,YAAY,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC,EAAE,CAAC,CAAC;AAEvH,MAAM,KAAK,GAAG,CAA4C,IAAO,EAAE,OAAU,EAAE,EAAE,CAChF,YAAY,CAAC;IACZ,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC;IACzC,aAAa,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAC9B,OAAO,EAAE,YAAY;IACrB,KAAK,EAAE,YAAY;IACnB,GAAG,EAAE,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;IACD,KAAK,CACJ,aAAa,EACb,YAAY,CAAC;QACZ,OAAO,EAAE,GAAG,CAAC,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,gBAAgB,EAAE,aAAa,CAAC;QACjF,YAAY,EAAE,IAAI,CAAC,QAAQ,CAAC,sBAAsB,CAAC;QACnD,cAAc,EAAE,IAAI,CAAC,OAAO,EAAE;QAC9B,6FAA6F;QAC7F,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;QACjF,MAAM,EAAE,aAAa,CAAC,UAAU,CAAC;KACjC,CAAC,CACF;CACD,CAAC,CAAC;AAGH,MAAM,SAAS,GAAG,WAAW,CAAC,iBAAiB,CAAC,CAAC;AAEjD,uGAAuG;AACvG,SAAS,gBAAgB,CAAC,GAAgB;IACzC,IAAI,GAAG,CAAC,IAAI,KAAK,eAAe;QAC/B,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,YAAY,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC;IACtF,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,OAAO,CAAC,KAAc;IAC9B,OAAO,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC9C,OAAO,aAAa,CAAC,eAAe,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import { type Static, type TSchema, Type } from \"typebox\";\nimport {\n\tcompileFlow,\n\tFLOW_ID_PATTERN,\n\tFlowCountSchema,\n\tFlowDigestSchema,\n\tFlowFailureClassSchema,\n\tFlowIdSchema,\n\tFlowMicrousdSchema,\n\tFlowPositiveIntSchema,\n\tFlowProfileRefSchema,\n\tFlowReasonClassSchema,\n\tFlowRoleSchema,\n\tFlowSizeSchema,\n\tFlowTimestampSchema,\n\tlit,\n\tparseFlowData,\n\tpartialByRole,\n\tStrictObject,\n} from \"./flow-common.ts\";\n\nexport { FlowProfileRefSchema, type FlowProfileRefV1 } from \"./flow-common.ts\";\n\n/**\n * Privacy rule: every string in an event is an Id, a Digest, an enum literal, or an ISO timestamp.\n * There is no free-text field, so prompts, messages and model output have no place to go. Syntax checks cannot tell\n * semantic content, though: a path-like string can match an Id or model pattern. Producers must put only catalog\n * provider/model identifiers in those fields (see docs/flow-contracts.md, trust boundaries).\n */\n\nexport const FLOW_EVENT_KINDS = [\n\t\"run_started\",\n\t\"size_decided\",\n\t\"escalated\",\n\t\"route_bound\",\n\t\"fallback\",\n\t\"attempt\",\n\t\"request_usage\",\n\t\"verdict\",\n\t\"budget\",\n\t\"control\",\n\t\"message\",\n\t\"run_settled\",\n] as const;\nexport type FlowEventKind = (typeof FLOW_EVENT_KINDS)[number];\n\nconst Mode = lit(\"auto\", \"direct\");\nconst Effort = lit(\"low\", \"medium\", \"high\");\nconst EventModelRefSchema = StrictObject({ provider: FlowIdSchema, model: Type.String({ pattern: FLOW_ID_PATTERN }) });\n\nconst event = <const K extends string, P extends TSchema>(kind: K, payload: P) =>\n\tStrictObject({\n\t\tschema: Type.Literal(\"humain-flow-event\"),\n\t\tschemaVersion: Type.Literal(1),\n\t\teventId: FlowIdSchema,\n\t\trunId: FlowIdSchema,\n\t\tseq: FlowPositiveIntSchema,\n\t\tts: FlowTimestampSchema,\n\t\tprofile: FlowProfileRefSchema,\n\t\tcauses: Type.Array(FlowIdSchema, { maxItems: 16 }),\n\t\tkind: Type.Literal(kind),\n\t\tpayload,\n\t});\n\nconst RoleTotals = StrictObject({\n\ttokens: FlowCountSchema,\n\tcostMicrousd: FlowMicrousdSchema,\n\tdurationMs: FlowCountSchema,\n\trequests: FlowCountSchema,\n});\n\nexport const FlowEventV1Schema = Type.Union([\n\tevent(\n\t\t\"run_started\",\n\t\tStrictObject({\n\t\t\tmode: Mode,\n\t\t\tsurface: lit(\"cli\", \"web\"),\n\t\t\tadmissionDigest: FlowDigestSchema,\n\t\t\tinputsCount: FlowCountSchema,\n\t\t\tgoalSha256: FlowDigestSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"size_decided\",\n\t\tStrictObject({\n\t\t\tsize: FlowSizeSchema,\n\t\t\tsource: lit(\"rules\", \"triage\", \"override\"),\n\t\t\truleScore: Type.Number({ minimum: 0, maximum: 1_000_000 }),\n\t\t\tthresholds: StrictObject({\n\t\t\t\tmediumAt: Type.Number({ minimum: 0, maximum: 1_000_000 }),\n\t\t\t\tlargeAt: Type.Number({ minimum: 0, maximum: 1_000_000 }),\n\t\t\t}),\n\t\t}),\n\t),\n\tevent(\"escalated\", StrictObject({ from: FlowSizeSchema, to: FlowSizeSchema, reasonClass: FlowReasonClassSchema })),\n\tevent(\n\t\t\"route_bound\",\n\t\tStrictObject({\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tmodel: EventModelRefSchema,\n\t\t\teffort: Effort,\n\t\t\tbinding: lit(\"primary\", \"backup\", \"lead_selected\"),\n\t\t\tbackupIndex: Type.Integer({ minimum: 0, maximum: 7 }),\n\t\t}),\n\t),\n\tevent(\n\t\t\"fallback\",\n\t\tStrictObject({\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tfrom: EventModelRefSchema,\n\t\t\tto: EventModelRefSchema,\n\t\t\treasonClass: FlowReasonClassSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"attempt\",\n\t\tStrictObject({\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tattempt: FlowPositiveIntSchema,\n\t\t\tstate: lit(\"started\", \"succeeded\", \"failed\", \"retried\", \"cancelled\"),\n\t\t\tfailureClass: Type.Optional(FlowFailureClassSchema),\n\t\t}),\n\t),\n\tevent(\n\t\t\"request_usage\",\n\t\tStrictObject({\n\t\t\trequestId: FlowIdSchema,\n\t\t\ttaskId: FlowIdSchema,\n\t\t\trole: FlowRoleSchema,\n\t\t\tmodel: EventModelRefSchema,\n\t\t\tinputTokens: FlowCountSchema,\n\t\t\toutputTokens: FlowCountSchema,\n\t\t\tcacheReadTokens: FlowCountSchema,\n\t\t\tcacheWriteTokens: FlowCountSchema,\n\t\t\tcostMicrousd: Type.Union([FlowMicrousdSchema, Type.Null()]),\n\t\t\tcostBasis: lit(\"reported\", \"estimated\", \"unknown\"),\n\t\t\tdurationMs: FlowCountSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"verdict\",\n\t\tStrictObject({\n\t\t\tstage: lit(\"check\", \"review\", \"qa\"),\n\t\t\ttaskId: FlowIdSchema,\n\t\t\tverdict: lit(\"pass\", \"fail\", \"blocked\"),\n\t\t\tfindingsCount: FlowCountSchema,\n\t\t\tcheckId: Type.Optional(FlowIdSchema),\n\t\t}),\n\t),\n\tevent(\n\t\t\"budget\",\n\t\tStrictObject({\n\t\t\tspentMicrousd: FlowMicrousdSchema,\n\t\t\tcapMicrousd: FlowMicrousdSchema,\n\t\t\tpct: Type.Number({ minimum: 0, maximum: 100 }),\n\t\t\tstate: lit(\"ok\", \"warn\", \"stop\"),\n\t\t}),\n\t),\n\tevent(\n\t\t\"control\",\n\t\tStrictObject({\n\t\t\taction: lit(\"pause\", \"resume\", \"cancel\", \"message\", \"status\"),\n\t\t\tcommandId: FlowIdSchema,\n\t\t\tstate: lit(\"accepted\", \"applied\", \"rejected\"),\n\t\t\tlatencyMs: FlowCountSchema,\n\t\t}),\n\t),\n\tevent(\n\t\t\"message\",\n\t\tStrictObject({\n\t\t\tmessageId: FlowIdSchema,\n\t\t\tdisposition: lit(\"live\", \"queued\", \"rejected\"),\n\t\t\ttargetRole: FlowRoleSchema,\n\t\t\ttextSha256: FlowDigestSchema,\n\t\t\ttextLength: Type.Integer({ minimum: 1, maximum: 16_000 }),\n\t\t}),\n\t),\n\tevent(\n\t\t\"run_settled\",\n\t\tStrictObject({\n\t\t\toutcome: lit(\"succeeded\", \"failed\", \"cancelled\", \"budget_stopped\", \"interrupted\"),\n\t\t\tfailureClass: Type.Optional(FlowFailureClassSchema),\n\t\t\tsettledCleanly: Type.Boolean(),\n\t\t\t// Subset of the two retry modes offered to the user; unique, order-free (full offer = both).\n\t\t\tretryOffer: Type.Array(lit(\"flow\", \"direct\"), { maxItems: 2, uniqueItems: true }),\n\t\t\ttotals: partialByRole(RoleTotals),\n\t\t}),\n\t),\n]);\nexport type FlowEventV1 = Static<typeof FlowEventV1Schema>;\n\nconst Validator = compileFlow(FlowEventV1Schema);\n\n/** `request_usage.costMicrousd` is null exactly when `costBasis` is \"unknown\"; never 0 for unknown. */\nfunction crossFieldsValid(doc: FlowEventV1): boolean {\n\tif (doc.kind === \"request_usage\")\n\t\treturn (doc.payload.costMicrousd === null) === (doc.payload.costBasis === \"unknown\");\n\treturn true;\n}\n\nfunction isEvent(value: unknown): value is FlowEventV1 {\n\treturn Validator.Check(value) && crossFieldsValid(value);\n}\n\n/** Validates a plain-data snapshot of `input` and returns the snapshot (never the caller's object). */\nexport function parseFlowEventV1(input: unknown): FlowEventV1 {\n\treturn parseFlowData(\"event_invalid\", input, isEvent);\n}\n"]}
|
package/dist/flow-sizing.d.ts
CHANGED
|
@@ -3,12 +3,14 @@ export type IntentDecisionSource = "keyword-classifier" | "mode-override" | "def
|
|
|
3
3
|
export type FlowSize = "small" | "medium" | "large";
|
|
4
4
|
export type RiskReason = "explicit-thorough-request" | "high-risk-domain-term" | "long-multi-imperative";
|
|
5
5
|
export type PromptExecutionDepth = "quick" | "balanced" | "thorough";
|
|
6
|
-
export
|
|
6
|
+
export type PromptDepthReason = "empty-prompt" | "explicit-thorough-request" | "high-risk-complexity" | "long-multi-imperative" | "non-implementation-desire" | "bounded-edit" | "hello-world-starter" | "complexity-signal" | "substantive-change" | "non-latin-complexity" | "long-multi-change" | "multi-change" | "default-quick";
|
|
7
|
+
export declare const UNIFIED_CLASSIFIER_POLICY_ID: "unified-regex-v5";
|
|
7
8
|
export interface UnifiedPromptClassification {
|
|
8
9
|
lane: IntentLane;
|
|
9
10
|
laneDecisionSource: IntentDecisionSource;
|
|
10
11
|
laneMatchedSignals: string[];
|
|
11
12
|
depth: PromptExecutionDepth;
|
|
13
|
+
depthReason: PromptDepthReason;
|
|
12
14
|
riskReasons: RiskReason[];
|
|
13
15
|
policyId: typeof UNIFIED_CLASSIFIER_POLICY_ID;
|
|
14
16
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow-sizing.d.ts","sourceRoot":"","sources":["../src/flow-sizing.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,YAAY,GAAG,UAAU,GAAG,UAAU,CAAC;AAC1E,MAAM,MAAM,oBAAoB,GAAG,oBAAoB,GAAG,eAAe,GAAG,SAAS,CAAC;AACtF,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,QAAQ,GAAG,OAAO,CAAC;AAmBpD,MAAM,MAAM,UAAU,GACnB,2BAA2B,GAC3B,uBAAuB,GACvB,uBAAuB,CAAC;AAE3B,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,UAAU,GAAG,UAAU,CAAC;AAErE,eAAO,MAAM,4BAA4B,EAAG,kBAA2B,CAAC;AAExE,MAAM,WAAW,2BAA2B;IAC3C,IAAI,EAAE,UAAU,CAAC;IACjB,kBAAkB,EAAE,oBAAoB,CAAC;IACzC,kBAAkB,EAAE,MAAM,EAAE,CAAC;IAC7B,KAAK,EAAE,oBAAoB,CAAC;IAC5B,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,QAAQ,EAAE,OAAO,4BAA4B,CAAC;CAC9C;
|
|
1
|
+
{"version":3,"file":"flow-sizing.d.ts","sourceRoot":"","sources":["../src/flow-sizing.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,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AgB,aAAa,CAAC,KAAK,EAAE,oBAAoB,EAAE,UAAU,CAAC,EAAE,kBAAkB,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,QAAQ,CAOpH"}
|
package/dist/flow-sizing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const UNIFIED_CLASSIFIER_POLICY_ID = "unified-regex-
|
|
1
|
+
export const UNIFIED_CLASSIFIER_POLICY_ID = "unified-regex-v5";
|
|
2
2
|
// ─── Lane signals (moved verbatim from packages/ai/src/intent/classifier.ts) ───
|
|
3
3
|
// Lane order mirrors the router lane rubric: DEBUG is checked first, then
|
|
4
4
|
// MECHANICAL, then CREATIVE; FALLBACK catches the rest.
|
|
@@ -7,9 +7,9 @@ const MECHANICAL_SIGNALS = /\b(alphabetize|async\/await|bump|comment out|convert
|
|
|
7
7
|
const CREATIVE_SIGNALS = /\b(add|build|component|create|dashboard|design|enhance|feature|flow|generate|implement|improve|integrate|interface|landing|new|page|portal|redesign|screen|section|tool|view|widget|workflow)\b/i;
|
|
8
8
|
const NAMED_MODE_OVERRIDES = new Set(["production-ready", "add-tests", "code-review", "create-prd"]);
|
|
9
9
|
// ─── Depth signals (moved verbatim from apps/web/lib/ai-modes.ts) ───
|
|
10
|
-
const COMPLEX_BUILD_RE = /\b(admin|analytics|api|auth|authentication|authorization|backend|calendar|charts?|crud|dashboard|database|deploy|deployment|e2e|end[-\s]?to[-\s]?end|full[-\s]?stack|integration|kanban|multi[-\s]?page|permissions?|production|reports?|roles?|security|tests?|workflow)\b/i;
|
|
10
|
+
const COMPLEX_BUILD_RE = /\b(admin|analytics|api|auth|authentication|authorization|backend|calendar|charts?|crud|dashboard|database|deploy|deployment|e2e|end[-\s]?to[-\s]?end|full[-\s]?stack|integration|kanban|multi[-\s]?(?:page|section|service)|(?:[2-9]|[1-9]\d+|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|multiple|several)\s+sections|permissions?|production|reports?|roles?|security|tests?|workflow)\b/i;
|
|
11
11
|
const EXPLICIT_THOROUGH_BUILD_RE = /\b(use\s+opus|opus[-\s]?level|thorough|deep(?:est)?\s+reasoning|deep\s+review|architecture\s+review)\b/i;
|
|
12
|
-
const HIGH_RISK_BUILD_RE = /\b(threat\s+model|security\s+review|compliance|regulated|hipaa|soc\s*2|gdpr|pci|data\s+retention|data\s+migration|schema\s+migration|tenant\s+isolation|multi[-\s]?tenant\s+authorization|authorization\s+architecture|incident\s+recovery|rollback\s+plan|payments?|billing)\b/i;
|
|
12
|
+
const HIGH_RISK_BUILD_RE = /\b(threat\s+model|security\s+review|compliance|regulated|hipaa|soc\s*2|gdpr|pci|data\s+retention|data\s+migration|schema\s+migration|migrat(?:e|es|ed|ing)\s+(?:(?:the|a|an|our|your)\s+)?database\s+schema|tenant\s+isolation|multi[-\s]?tenant\s+authorization|authorization\s+architecture|incident\s+recovery|rollback\s+plan|payments?|billing)\b/i;
|
|
13
13
|
const SUBSTANTIVE_CHANGE_ACTION_SOURCE = "add|build|change|connect|configure|create|design|develop|enable|enhance|extend|fix|generate|implement|improve|integrate|introduce|make|redesign|refactor|remove|rename|replace|set\\s+up|support|update|wire";
|
|
14
14
|
const FOLLOW_UP_CHANGE_ACTION_SOURCE = `${SUBSTANTIVE_CHANGE_ACTION_SOURCE}|allow|automate|calculate|delete|display|export|give|handle|hide|import|invite|launch|let|localize|manage|move|permit|process|provide|rename|search|share|show|sync|track|trigger|unlock`;
|
|
15
15
|
const FOLLOW_UP_CHANGE_BOUNDARY_SOURCE = "(?:\\b(?:and|also|plus|additionally|then)\\b|[,;:.!?]|\\s(?:/|-|–|—)\\s)";
|
|
@@ -26,6 +26,9 @@ const LINE_TERMINATORS = "\\n\\r\\u2028\\u2029";
|
|
|
26
26
|
*/
|
|
27
27
|
const spacedSpan = (tail) => `(?:\\s+\\S(?:[^${LINE_TERMINATORS}]*\\S)?\\s+|\\s[${LINE_TERMINATORS}]*[^\\S${LINE_TERMINATORS}]\\s+)${tail}`;
|
|
28
28
|
const SUBSTANTIVE_CHANGE_REQUEST_RE = new RegExp(`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:(?:(?:can|could|should|would|will)\\s+(?:you|we)\\s+|(?:i|we)(?:['’]d| would)?\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like(?:\\s+you)?\\s+to\\s+|i\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}want(?:\\s+you)?\\s+to\\s+|we\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:need(?:\\s+you)?\\s+to|should|must)\\s+|let['’]?s\\s+)${REQUEST_DISCOURSE_MODIFIER_SOURCE})?(${SUBSTANTIVE_CHANGE_ACTION_SOURCE})\\b`, "i");
|
|
29
|
+
// Check the raw entire target, not quote-masked text: a quoted suffix must not disappear into the starter exception.
|
|
30
|
+
const HELLO_WORLD_STARTER_ACTION_RE = /^(?:build|create|develop|generate|implement|make)$/i;
|
|
31
|
+
const HELLO_WORLD_STARTER_TARGET_RE = /^(?:(?:a|an|the)\s+)?(?:(?:basic|minimal|simple)\s+)?hello[-\s]+world(?:\s+(?:app|application|demo|example|page|program|starter))?[.!?]*$/i;
|
|
29
32
|
const DESIRED_STATE_REQUEST_RES = [
|
|
30
33
|
new RegExp(`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:i|we)(?:['’]d\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like|\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:want|need|would\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like))\\s+(?=\\S)(.+)$`, "i"),
|
|
31
34
|
new RegExp(`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}can\\s+(?:we|you)\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}have\\s+(?=\\S)(.+)$`, "i"),
|
|
@@ -63,7 +66,7 @@ const POTENTIALLY_BOUNDED_ACTIONS = new Set([
|
|
|
63
66
|
"replace",
|
|
64
67
|
"update",
|
|
65
68
|
]);
|
|
66
|
-
const BOUNDED_EDIT_TARGET_SOURCE = "alignment|border|caption|
|
|
69
|
+
const BOUNDED_EDIT_TARGET_SOURCE = "alignment|border|caption|colou?r|copy|description|font|gap|heading|icon|label|link|margin|padding|placeholder|punctuation|radius|shadow|size|spacing|subtitle|text|title|tooltip|typo|weight|wording";
|
|
67
70
|
const BOUNDED_EDIT_TARGET_RE = new RegExp(`^(?:(?:the|a|an)\\s+)?((?:[\\w-]+\\s+){0,5})(${BOUNDED_EDIT_TARGET_SOURCE})\\b(.*)$`, "i");
|
|
68
71
|
const COORDINATED_BOUNDED_EDIT_TARGET_TAIL_RE = new RegExp(`(?:(?:and|also|plus|additionally)\\s+)?(?:(?:the|a|an)\\s+)?(?:[\\w-]+\\s+){0,5}(?:${BOUNDED_EDIT_TARGET_SOURCE})\\b`, "iy");
|
|
69
72
|
const BOUNDED_UI_SURFACE_MODIFIER_RE = /\b(app|application|badge|banner|breadcrumb|button|card|chip|control|dialog|drawer|dropdown|field|footer|form|header|hero|input|list|logo|menu|modal|nav|navbar|navigation|page|panel|popover|row|screen|search|section|select|shell|sidebar|switch|tab|table|tile|toast|toggle|toolbar)\b/i;
|
|
@@ -324,6 +327,8 @@ function isBoundedEditTarget(target, action) {
|
|
|
324
327
|
if (!match)
|
|
325
328
|
return false;
|
|
326
329
|
const modifiers = match[1]?.trim() ?? "";
|
|
330
|
+
if (BOUNDED_LOCATION_PURPOSE_RE.test(modifiers) || FUNCTIONAL_PURPOSE_CLAUSE_RE.test(modifiers))
|
|
331
|
+
return false;
|
|
327
332
|
if ((!action || action === "add") &&
|
|
328
333
|
CAPABILITY_CONTAINER_MODIFIER_RE.test(modifiers) &&
|
|
329
334
|
!BOUNDED_UI_SURFACE_MODIFIER_RE.test(modifiers)) {
|
|
@@ -490,29 +495,37 @@ function classifyChangeRequest(prompt) {
|
|
|
490
495
|
}
|
|
491
496
|
function resolvePromptExecutionDepth(trimmed, signalText, imperativeTotal, changeRequestKind) {
|
|
492
497
|
if (!trimmed)
|
|
493
|
-
return "quick";
|
|
494
|
-
if (EXPLICIT_THOROUGH_BUILD_RE.test(signalText))
|
|
495
|
-
return "thorough";
|
|
498
|
+
return { depth: "quick", depthReason: "empty-prompt" };
|
|
499
|
+
if (EXPLICIT_THOROUGH_BUILD_RE.test(signalText)) {
|
|
500
|
+
return { depth: "thorough", depthReason: "explicit-thorough-request" };
|
|
501
|
+
}
|
|
496
502
|
if (HIGH_RISK_BUILD_RE.test(signalText) && (COMPLEX_BUILD_RE.test(signalText) || imperativeTotal >= 2)) {
|
|
497
|
-
return "thorough";
|
|
503
|
+
return { depth: "thorough", depthReason: "high-risk-complexity" };
|
|
504
|
+
}
|
|
505
|
+
if (signalText.length > 600 && imperativeTotal >= 3) {
|
|
506
|
+
return { depth: "thorough", depthReason: "long-multi-imperative" };
|
|
498
507
|
}
|
|
499
|
-
if (signalText.length > 600 && imperativeTotal >= 3)
|
|
500
|
-
return "thorough";
|
|
501
508
|
if (hasNonImplementationDesire(trimmed))
|
|
502
|
-
return "quick";
|
|
509
|
+
return { depth: "quick", depthReason: "non-implementation-desire" };
|
|
503
510
|
if (changeRequestKind === "bounded")
|
|
504
|
-
return "quick";
|
|
511
|
+
return { depth: "quick", depthReason: "bounded-edit" };
|
|
512
|
+
const starterRequest = SUBSTANTIVE_CHANGE_REQUEST_RE.exec(trimmed);
|
|
513
|
+
if (starterRequest &&
|
|
514
|
+
HELLO_WORLD_STARTER_ACTION_RE.test(starterRequest[1] ?? "") &&
|
|
515
|
+
HELLO_WORLD_STARTER_TARGET_RE.test(trimmed.slice(starterRequest[0].length).trim())) {
|
|
516
|
+
return { depth: "quick", depthReason: "hello-world-starter" };
|
|
517
|
+
}
|
|
505
518
|
if (COMPLEX_BUILD_RE.test(signalText))
|
|
506
|
-
return "balanced";
|
|
519
|
+
return { depth: "balanced", depthReason: "complexity-signal" };
|
|
507
520
|
if (changeRequestKind === "substantive")
|
|
508
|
-
return "balanced";
|
|
521
|
+
return { depth: "balanced", depthReason: "substantive-change" };
|
|
509
522
|
if (hasNonLatinComplexitySignal(signalText))
|
|
510
|
-
return "balanced";
|
|
523
|
+
return { depth: "balanced", depthReason: "non-latin-complexity" };
|
|
511
524
|
if (signalText.length > 180 && imperativeTotal >= 2)
|
|
512
|
-
return "balanced";
|
|
525
|
+
return { depth: "balanced", depthReason: "long-multi-change" };
|
|
513
526
|
if (hasMultiChangePrompt(signalText))
|
|
514
|
-
return "balanced";
|
|
515
|
-
return "quick";
|
|
527
|
+
return { depth: "balanced", depthReason: "multi-change" };
|
|
528
|
+
return { depth: "quick", depthReason: "default-quick" };
|
|
516
529
|
}
|
|
517
530
|
// Independent of the resolved depth: a prompt can carry a risk signal (e.g.
|
|
518
531
|
// a high-risk domain term) even on a turn where the overall heuristic above
|
|
@@ -545,7 +558,7 @@ export function classifyPromptSignals(input) {
|
|
|
545
558
|
lane: laneResult.lane,
|
|
546
559
|
laneDecisionSource: laneResult.decisionSource,
|
|
547
560
|
laneMatchedSignals: laneResult.matchedSignals,
|
|
548
|
-
|
|
561
|
+
...resolvePromptExecutionDepth(trimmed, signalText, imperativeTotal, changeRequestKind),
|
|
549
562
|
riskReasons: computeRiskReasons(signalText, imperativeTotal),
|
|
550
563
|
policyId: UNIFIED_CLASSIFIER_POLICY_ID,
|
|
551
564
|
};
|
package/dist/flow-sizing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow-sizing.js","sourceRoot":"","sources":["../src/flow-sizing.ts"],"names":[],"mappings":"AA4BA,MAAM,CAAC,MAAM,4BAA4B,GAAG,kBAA2B,CAAC;AAWxE,kFAAkF;AAClF,0EAA0E;AAC1E,wDAAwD;AACxD,MAAM,aAAa,GAClB,yRAAyR,CAAC;AAE3R,MAAM,kBAAkB,GACvB,2NAA2N,CAAC;AAE7N,MAAM,gBAAgB,GACrB,kMAAkM,CAAC;AAEpM,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,kBAAkB,EAAE,WAAW,EAA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,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;IAC1D,CAAC;IACD,IAAI,KAAK,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC;IACzC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;AAClD,CAAC","sourcesContent":["export type IntentLane = \"debug\" | \"mechanical\" | \"creative\" | \"fallback\";\nexport type IntentDecisionSource = \"keyword-classifier\" | \"mode-override\" | \"default\";\nexport type FlowSize = \"small\" | \"medium\" | \"large\";\n\n// One browser-safe classifier for both the build-depth heuristic\n// (apps/web/lib/ai-modes.ts) and the skill/router intent lane\n// (packages/ai/src/intent/classifier.ts). The D1 golden fixture\n// (packages/ai/src/intent/__fixtures__/unified-classifier-golden.json)\n// preserves the pre-refactor behavior; intentional classifier changes are\n// versioned through UNIFIED_CLASSIFIER_POLICY_ID and focused regression tables.\n//\n// This module centralizes IMPLEMENTATION, not INPUTS: depth and skill-lane\n// consumers may still classify different prompt variants (e.g.\n// attachment-enriched vs. base prompt text) than each other. Unifying what\n// text each caller feeds in is out of scope here — that is the deliberately\n// cut 1-exp-A scope, not this task.\n//\n// Moved from Forge packages/ai/src/intent/unified-classifier.ts (single source of\n// truth for the CLI and the web). This module must have NO imports at all: it is\n// browser-safe and dependency-free (enforced by scripts/check-entry-graphs.mjs).\n\nexport type RiskReason =\n\t| \"explicit-thorough-request\" // EXPLICIT_THOROUGH_BUILD_RE\n\t| \"high-risk-domain-term\" // HIGH_RISK_BUILD_RE\n\t| \"long-multi-imperative\"; // >600 chars + >=3 imperatives\n\nexport type PromptExecutionDepth = \"quick\" | \"balanced\" | \"thorough\";\n\nexport const UNIFIED_CLASSIFIER_POLICY_ID = \"unified-regex-v4\" as const;\n\nexport interface UnifiedPromptClassification {\n\tlane: IntentLane;\n\tlaneDecisionSource: IntentDecisionSource;\n\tlaneMatchedSignals: string[];\n\tdepth: PromptExecutionDepth;\n\triskReasons: RiskReason[];\n\tpolicyId: typeof UNIFIED_CLASSIFIER_POLICY_ID;\n}\n\n// ─── Lane signals (moved verbatim from packages/ai/src/intent/classifier.ts) ───\n// Lane order mirrors the router lane rubric: DEBUG is checked first, then\n// MECHANICAL, then CREATIVE; FALLBACK catches the rest.\nconst DEBUG_SIGNALS =\n\t/\\b(404|500|broken|bug|crash(?:es|ed|ing)?|debug(?:s|ged|ging)?|diagnos(?:e|es|ed|ing)|doesn'?t work|error|exception|fail(?:s|ed|ing)?|failing|flaky|null|not working|regression|root cause|stack trace|troubleshoot(?:s|ed|ing)?|undefined|unexpected|wrong (?:output|result|value))\\b/i;\n\nconst MECHANICAL_SIGNALS =\n\t/\\b(alphabetize|async\\/await|bump|comment out|convert|delete unused|explain|extract (?:component|function)|inline|move (?:file|folder|component)|re-?format|re-?order|remove unused|rename|sort imports|typo|uncomment)\\b/i;\n\nconst CREATIVE_SIGNALS =\n\t/\\b(add|build|component|create|dashboard|design|enhance|feature|flow|generate|implement|improve|integrate|interface|landing|new|page|portal|redesign|screen|section|tool|view|widget|workflow)\\b/i;\n\nconst NAMED_MODE_OVERRIDES = new Set([\"production-ready\", \"add-tests\", \"code-review\", \"create-prd\"]);\n\n// ─── Depth signals (moved verbatim from apps/web/lib/ai-modes.ts) ───\nconst COMPLEX_BUILD_RE =\n\t/\\b(admin|analytics|api|auth|authentication|authorization|backend|calendar|charts?|crud|dashboard|database|deploy|deployment|e2e|end[-\\s]?to[-\\s]?end|full[-\\s]?stack|integration|kanban|multi[-\\s]?page|permissions?|production|reports?|roles?|security|tests?|workflow)\\b/i;\nconst EXPLICIT_THOROUGH_BUILD_RE =\n\t/\\b(use\\s+opus|opus[-\\s]?level|thorough|deep(?:est)?\\s+reasoning|deep\\s+review|architecture\\s+review)\\b/i;\nconst HIGH_RISK_BUILD_RE =\n\t/\\b(threat\\s+model|security\\s+review|compliance|regulated|hipaa|soc\\s*2|gdpr|pci|data\\s+retention|data\\s+migration|schema\\s+migration|tenant\\s+isolation|multi[-\\s]?tenant\\s+authorization|authorization\\s+architecture|incident\\s+recovery|rollback\\s+plan|payments?|billing)\\b/i;\nconst SUBSTANTIVE_CHANGE_ACTION_SOURCE =\n\t\"add|build|change|connect|configure|create|design|develop|enable|enhance|extend|fix|generate|implement|improve|integrate|introduce|make|redesign|refactor|remove|rename|replace|set\\\\s+up|support|update|wire\";\nconst FOLLOW_UP_CHANGE_ACTION_SOURCE = `${SUBSTANTIVE_CHANGE_ACTION_SOURCE}|allow|automate|calculate|delete|display|export|give|handle|hide|import|invite|launch|let|localize|manage|move|permit|process|provide|rename|search|share|show|sync|track|trigger|unlock`;\nconst FOLLOW_UP_CHANGE_BOUNDARY_SOURCE = \"(?:\\\\b(?:and|also|plus|additionally|then)\\\\b|[,;:.!?]|\\\\s(?:/|-|–|—)\\\\s)\";\nconst FOLLOW_UP_CHANGE_BOUNDARY_RE = new RegExp(FOLLOW_UP_CHANGE_BOUNDARY_SOURCE, \"i\");\nconst LOCATION_REFERENCE_CONJUNCTION_RE = /^and$/i;\nconst REQUEST_DISCOURSE_MODIFIER_SOURCE = \"(?:(?:just|kindly|only|please|simply)\\\\s+)*\";\n// Regex hardening (linear time): adjacent modifier runs are merged because `M* M*` is ambiguous, and\n// `\\s+.+\\s+TAIL` spans use `spacedSpan` below. Every rewrite keeps the original language; see test/flow-sizing.test.ts.\nconst LINE_TERMINATORS = \"\\\\n\\\\r\\\\u2028\\\\u2029\";\n/**\n * Linear form of `\\s+.+\\s+TAIL` where TAIL starts with a non-space and `.` excludes line terminators: either the\n * span starts and ends on non-space characters (the whitespace runs absorb everything else), or it is a single\n * horizontal space inside one whitespace run.\n */\nconst spacedSpan = (tail: string) =>\n\t`(?:\\\\s+\\\\S(?:[^${LINE_TERMINATORS}]*\\\\S)?\\\\s+|\\\\s[${LINE_TERMINATORS}]*[^\\\\S${LINE_TERMINATORS}]\\\\s+)${tail}`;\nconst SUBSTANTIVE_CHANGE_REQUEST_RE = new RegExp(\n\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:(?:(?:can|could|should|would|will)\\\\s+(?:you|we)\\\\s+|(?:i|we)(?:['’]d| would)?\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like(?:\\\\s+you)?\\\\s+to\\\\s+|i\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}want(?:\\\\s+you)?\\\\s+to\\\\s+|we\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:need(?:\\\\s+you)?\\\\s+to|should|must)\\\\s+|let['’]?s\\\\s+)${REQUEST_DISCOURSE_MODIFIER_SOURCE})?(${SUBSTANTIVE_CHANGE_ACTION_SOURCE})\\\\b`,\n\t\"i\",\n);\nconst DESIRED_STATE_REQUEST_RES = [\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:i|we)(?:['’]d\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like|\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:want|need|would\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like))\\\\s+(?=\\\\S)(.+)$`,\n\t\t\"i\",\n\t),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}can\\\\s+(?:we|you)\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}have\\\\s+(?=\\\\S)(.+)$`,\n\t\t\"i\",\n\t),\n\tnew RegExp(`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:allow|enable|let)${spacedSpan(\"to\\\\b\")}`, \"i\"),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:give|provide)${spacedSpan(\"(?:a\\\\s+way|the\\\\s+ability)\\\\s+to\\\\b\")}`,\n\t\t\"i\",\n\t),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?!i\\\\b|we\\\\b|you\\\\b)(?:[\\\\w-]+\\\\s+){1,5}(?:should|must|need(?:s)?\\\\s+to)\\\\s+be\\\\s+able\\\\s+to\\\\b`,\n\t\t\"i\",\n\t),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:a|an|the)${spacedSpan(\"(?:should|must|need(?:s)?\\\\s+to)\\\\s+(?:be\\\\s+(?:added|built|created|implemented|integrated|introduced|supported)\\\\b|(?:allow|enable|have|include|provide|support)\\\\b)\")}`,\n\t\t\"i\",\n\t),\n] as const;\nconst NON_IMPLEMENTATION_DESIRE_BOUNDARY_SOURCE =\n\t\"(?=[.!?]*$|\\\\s+(?:about|of|on|regarding|whether)\\\\b|\\\\s*(?:[,;:]|\\\\b(?:and|also|plus|additionally|then)\\\\b)|\\\\s+(?:-|–|—)\\\\s+)\";\nconst NON_IMPLEMENTATION_DESIRE_RE = new RegExp(\n\t`^(?:to\\\\s+(?:consider|decide|discuss|explore|know|learn|review|understand|wonder)\\\\b|help\\\\s+(?:with\\\\s+)?(?:considering|deciding|discussing|exploring|learning|reviewing|understanding)\\\\b|(?:advice|feedback)${NON_IMPLEMENTATION_DESIRE_BOUNDARY_SOURCE}|(?:a|an|the)\\\\s+(?:analysis|conversation|discussion|explanation|overview|review|summary)${NON_IMPLEMENTATION_DESIRE_BOUNDARY_SOURCE})`,\n\t\"i\",\n);\nconst NON_IMPLEMENTATION_TOPIC_RE =\n\t/^(?:(?:advice|feedback)|(?:a|an|the)\\s+(?:analysis|conversation|discussion|explanation|overview|review|summary))\\s+(?:about|of|on|regarding|whether)\\b/i;\nconst LEADING_ADVISORY_REQUEST_RE = new RegExp(\n\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:(?:can|could|would|will)\\\\s+(?:you|we)\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE})?(?:analy[sz]e|assess|describe|discuss|explain|explore|review|summarize|tell\\\\s+(?:me|us)|walk\\\\s+(?:me|us)\\\\s+through|give\\\\s+(?:me|us)\\\\s+(?:advice|feedback)|provide\\\\s+(?:me|us)\\\\s+(?:advice|feedback)|help\\\\s+(?:me|us)\\\\s+understand)\\\\b`,\n\t\"i\",\n);\nconst ADVISORY_OUTPUT_ACTIONS = new Set([\"give\", \"provide\", \"show\"]);\nconst ADVISORY_TOPIC_COMPOUND_ACTION_RE =\n\t/^(?:build|change|create|design|export|import|process|search|support|update)$/;\nconst ADVISORY_TOPIC_COMPOUND_HEAD_RE =\n\t/^(?:approach|architecture|consistency|conventions?|coverage|experience|flows?|governance|management|patterns?|performance|process(?:es)?|quality|reliability|security|standards?|strategy|structure|tooling|usability|workflows?)\\b/i;\nconst EXPLICIT_FOLLOW_UP_REQUEST_RE =\n\t/\\b(?:just|kindly|only|please|simply|then)\\b|[;:]|(?:can|could|would|will)\\s+(?:you|we)\\b/i;\nconst ADVISORY_OUTPUT_TARGET_RE =\n\t/^(?:(?:me|us)\\s+)?(?:(?:a|an|more|some|the|your)\\s+)?(?:(?:advice|analysis|assessment|conversation|discussion|explanation|feedback|findings?|next\\s+steps|options?|overview|recommendations?|review|suggestions?|summary|thoughts?|trade[-\\s]?offs?)(?:\\s+(?:about|of|on|regarding)\\s+(?=\\S).+)?|(?:how|what|whether|why)\\b.+)$/i;\nconst ADVISORY_OUTPUT_REQUEST_RE = /^(?:give|provide|show)\\s+(?=\\S)(.+)$/i;\nconst FOLLOW_UP_PREFIX_RE =\n\t/^[\\s,:;.!?/–—-]*(?:(?:and|also|plus|additionally|then)\\b[\\s,:;.!?/–—-]*)*(?:(?:just|kindly|only|please|simply)\\s+)*/i;\nconst COURTESY_ONLY_RE = /^(?:please|thanks|thank\\s+you)[.!?]*$/i;\n// Tail of a follow-up change clause, matched (sticky) where the punctuation/space run after a boundary ends.\nconst FOLLOW_UP_CHANGE_TAIL_RE = new RegExp(\n\t`${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:(?:can|could|would|will)\\\\s+(?:you|we)\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE})?(${FOLLOW_UP_CHANGE_ACTION_SOURCE})\\\\b(?=\\\\s+\\\\S)`,\n\t\"iy\",\n);\nconst LEADING_SUBSTANTIVE_CHANGE_VALUE_RE = new RegExp(`^(?:${FOLLOW_UP_CHANGE_ACTION_SOURCE})\\\\b\\\\s+\\\\S+`, \"i\");\nconst BOUNDED_COPY_CONNECTOR_RE = /\\b(?:and|by|or)\\b/i;\nconst BOUNDED_LOCATION_PURPOSE_RE = new RegExp(\n\t`\\\\b(?:in\\\\s+order\\\\s+)?to\\\\s+(?:${FOLLOW_UP_CHANGE_ACTION_SOURCE})\\\\b`,\n\t\"i\",\n);\nconst FUNCTIONAL_PURPOSE_CLAUSE_RE =\n\t/\\b(?:so(?:\\s+that)?\\s+\\S+(?:\\s+\\S+){0,2}\\s+(?:can|could|may|might|will|would)\\s+\\S+|that\\s+(?:allows?|enables?|lets?)\\s+\\S+\\s+\\S+|for\\s+\\S+(?:\\s+\\S+){0,2}\\s+to\\s+\\S+)\\b/i;\nconst POTENTIALLY_BOUNDED_ACTIONS = new Set([\n\t\"add\",\n\t\"change\",\n\t\"fix\",\n\t\"improve\",\n\t\"make\",\n\t\"remove\",\n\t\"rename\",\n\t\"replace\",\n\t\"update\",\n]);\nconst BOUNDED_EDIT_TARGET_SOURCE =\n\t\"alignment|border|caption|color|copy|description|font|gap|heading|icon|label|link|margin|padding|placeholder|punctuation|radius|shadow|size|spacing|subtitle|text|title|tooltip|typo|weight|wording\";\nconst BOUNDED_EDIT_TARGET_RE = new RegExp(\n\t`^(?:(?:the|a|an)\\\\s+)?((?:[\\\\w-]+\\\\s+){0,5})(${BOUNDED_EDIT_TARGET_SOURCE})\\\\b(.*)$`,\n\t\"i\",\n);\nconst COORDINATED_BOUNDED_EDIT_TARGET_TAIL_RE = new RegExp(\n\t`(?:(?:and|also|plus|additionally)\\\\s+)?(?:(?:the|a|an)\\\\s+)?(?:[\\\\w-]+\\\\s+){0,5}(?:${BOUNDED_EDIT_TARGET_SOURCE})\\\\b`,\n\t\"iy\",\n);\nconst BOUNDED_UI_SURFACE_MODIFIER_RE =\n\t/\\b(app|application|badge|banner|breadcrumb|button|card|chip|control|dialog|drawer|dropdown|field|footer|form|header|hero|input|list|logo|menu|modal|nav|navbar|navigation|page|panel|popover|row|screen|search|section|select|shell|sidebar|switch|tab|table|tile|toast|toggle|toolbar)\\b/i;\nconst CAPABILITY_CONTAINER_MODIFIER_RE =\n\t/\\b(assistant|builder|center|editor|engine|feature|flow|integration|manager|module|platform|service|system|tool|workflow)\\b/i;\nconst BOUNDED_PRESENTATION_ADJECTIVE_RE =\n\t/^(?:(?:a\\s+(?:bit|little)|much|slightly)\\s+)?(?:bolder|brighter|clearer|cooler|darker|friendlier|larger|lighter|longer|looser|rounder|sharper|shorter|smaller|softer|stronger|thicker|thinner|tighter|warmer|weaker|more\\s+(?:compact|concise|descriptive|prominent|readable|specific|visible))[.!?]*$/i;\nconst BOUNDED_LOCATION_RE =\n\t/^(?:after|around|at|before|below|beside|between|by|in|inside|near|next\\s+to|on|outside|right\\s+next\\s+to|under|within)\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_LOCATION_BOUNDARY_RE =\n\t/\\b(?:after|around|at|before|below|beside|between|by|in|inside|near|next\\s+to|on|outside|right\\s+next\\s+to|under|within)\\s+/i;\nconst BOUNDED_CONTENT_VALUE_RE = /^(?:read|say)\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_TO_VALUE_RE = /^to\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_FROM_TO_HEAD_RE = /^from\\s+(?=\\S)/i;\nconst BOUNDED_PRESENTATION_PAYLOAD_RE = /^with\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_PASSIVE_VALUE_RE = /^(?:changed|fixed|renamed|replaced|set|updated)\\s+(?:to|with)\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_PASSIVE_FROM_TO_HEAD_RE = /^(?:changed|renamed|replaced|updated)\\s+from\\s+(?=\\S)/i;\nconst FROM_TO_SEPARATOR_RE = /(?<=\\S)\\s+to\\s+(?=\\S)/gi;\nconst BOUNDED_PASSIVE_COMPLETED_RE = /^(?:changed|fixed|renamed|replaced|set|updated)[.!?]*$/i;\nconst BOUNDED_PASSIVE_PRESENTATION_RE = /^made\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_PASSIVE_REMOVAL_RE = /^(?:deleted|removed)[.!?]*$/i;\nconst BUILD_CONJUNCTION_RE = /\\b(and|also|plus|additionally)\\b/i;\nconst LIST_SEPARATOR_RE = /[,;،]/u;\nconst NON_LATIN_RE = /[^\\p{Script=Latin}\\p{Script=Common}\\p{Script=Inherited}]/u;\nconst ARABIC_COMPLEX_BUILD_RE = /(اختبارات|إعدادات|بيانات|تقارير|تحكم|صلاحيات|لوحة)/u;\nconst BUILD_IMPERATIVE_RES = [\n\t\"build\",\n\t\"create\",\n\t\"generate\",\n\t\"change\",\n\t\"make\",\n\t\"add\",\n\t\"remove\",\n\t\"delete\",\n\t\"update\",\n\t\"move\",\n\t\"replace\",\n\t\"fix\",\n\t\"implement\",\n\t\"wire\",\n].map((value) => new RegExp(`\\\\b${value}\\\\b`, \"gi\"));\n\nfunction matchSignals(prompt: string, pattern: RegExp): string[] {\n\tconst global = new RegExp(pattern.source, \"gi\");\n\treturn Array.from(new Set(Array.from(prompt.matchAll(global), (match) => match[0].toLowerCase())));\n}\n\ninterface LaneResult {\n\tlane: IntentLane;\n\tdecisionSource: IntentDecisionSource;\n\tmatchedSignals: string[];\n}\n\nfunction classifyLane(input: { prompt: string; mode?: string | null }): LaneResult {\n\tconst namedMode = input.mode?.trim();\n\tif (namedMode && NAMED_MODE_OVERRIDES.has(namedMode)) {\n\t\treturn {\n\t\t\tlane: \"creative\",\n\t\t\tdecisionSource: \"mode-override\",\n\t\t\tmatchedSignals: [`mode:${namedMode}`],\n\t\t};\n\t}\n\n\tconst prompt = input.prompt.trim();\n\tif (!prompt) return { lane: \"fallback\", decisionSource: \"default\", matchedSignals: [] };\n\n\tconst lanes: Array<{ lane: IntentLane; pattern: RegExp }> = [\n\t\t{ lane: \"debug\", pattern: DEBUG_SIGNALS },\n\t\t{ lane: \"mechanical\", pattern: MECHANICAL_SIGNALS },\n\t\t{ lane: \"creative\", pattern: CREATIVE_SIGNALS },\n\t];\n\tfor (const { lane, pattern } of lanes) {\n\t\tconst matchedSignals = matchSignals(prompt, pattern);\n\t\tif (matchedSignals.length > 0) {\n\t\t\treturn { lane, decisionSource: \"keyword-classifier\", matchedSignals };\n\t\t}\n\t}\n\treturn { lane: \"fallback\", decisionSource: \"default\", matchedSignals: [] };\n}\n\nfunction imperativeCount(prompt: string): number {\n\treturn BUILD_IMPERATIVE_RES.reduce((count, re) => {\n\t\tconst matches = prompt.match(re);\n\t\treturn count + (matches?.length ?? 0);\n\t}, 0);\n}\n\nfunction hasMultiChangePrompt(prompt: string): boolean {\n\tif (!BUILD_CONJUNCTION_RE.test(prompt)) return false;\n\treturn imperativeCount(prompt) >= 2;\n}\n\nfunction hasNonLatinComplexitySignal(prompt: string): boolean {\n\tif (!NON_LATIN_RE.test(prompt)) return false;\n\tif (ARABIC_COMPLEX_BUILD_RE.test(prompt)) return true;\n\treturn LIST_SEPARATOR_RE.test(prompt) && prompt.length > 48;\n}\n\nfunction isShortBoundedPhrase(value: string, maxWords: number): boolean {\n\tconst trimmed = value.trim();\n\tif (!trimmed || trimmed.length > 80 || /[\\r\\n;]/.test(trimmed)) return false;\n\tconst withoutTerminalPunctuation = trimmed.replace(/[.!?]+$/, \"\").trim();\n\tif (!withoutTerminalPunctuation || /[.!?]\\s/.test(withoutTerminalPunctuation)) return false;\n\treturn withoutTerminalPunctuation.split(/\\s+/).length <= maxWords;\n}\n\nconst QUOTE_PAIRS: Readonly<Record<string, string>> = {\n\t'\"': '\"',\n\t\"'\": \"'\",\n\t\"`\": \"`\",\n\t\"“\": \"”\",\n\t\"‘\": \"’\",\n};\n\nfunction isWordCharacterAt(value: string, index: number): boolean {\n\tconst character = value[index];\n\treturn character !== undefined && /[\\p{L}\\p{N}_]/u.test(character);\n}\n\nfunction maskQuotedText(value: string): string {\n\tconst masked = value.split(\"\");\n\t// An opener whose scan found no closer before the end of its line proves every later opener of the same\n\t// kind on that line also fails (closer validity does not depend on the opener), so it is skipped.\n\tconst noCloserBefore = new Map<string, number>();\n\n\tfor (let openingIndex = 0; openingIndex < value.length; openingIndex += 1) {\n\t\tconst opening = value[openingIndex] ?? \"\";\n\t\tconst closing = QUOTE_PAIRS[opening];\n\t\tif (!closing) continue;\n\n\t\tconst isSingleQuote = opening === \"'\" || opening === \"‘\";\n\t\tif (\n\t\t\tisSingleQuote &&\n\t\t\t(isWordCharacterAt(value, openingIndex - 1) ||\n\t\t\t\t!value[openingIndex + 1] ||\n\t\t\t\t/[\\s\\r\\n]/.test(value[openingIndex + 1] ?? \"\"))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((noCloserBefore.get(opening) ?? -1) > openingIndex) continue;\n\n\t\tlet closingIndex = openingIndex + 1;\n\t\tfor (; closingIndex < value.length; closingIndex += 1) {\n\t\t\tconst character = value[closingIndex];\n\t\t\tif (character === \"\\r\" || character === \"\\n\") break;\n\t\t\tif (character !== closing) continue;\n\t\t\tif (\n\t\t\t\tisSingleQuote &&\n\t\t\t\tisWordCharacterAt(value, closingIndex - 1) &&\n\t\t\t\tisWordCharacterAt(value, closingIndex + 1)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (let index = openingIndex; index <= closingIndex; index += 1) {\n\t\t\t\tmasked[index] = \" \";\n\t\t\t}\n\t\t\topeningIndex = closingIndex;\n\t\t\tbreak;\n\t\t}\n\t\tif (closingIndex >= value.length || value[closingIndex] === \"\\r\" || value[closingIndex] === \"\\n\") {\n\t\t\tnoCloserBefore.set(opening, closingIndex);\n\t\t}\n\t}\n\n\treturn masked.join(\"\");\n}\n\nfunction isEntireQuotedLiteral(value: string): boolean {\n\tconst trimmed = value.trim();\n\tconst opening = trimmed[0] ?? \"\";\n\tconst closing = QUOTE_PAIRS[opening];\n\treturn Boolean(closing && trimmed.length >= 2 && trimmed.at(-1) === closing);\n}\n\nconst FOLLOW_UP_BOUNDARY_G_RE = new RegExp(FOLLOW_UP_CHANGE_BOUNDARY_SOURCE, \"gi\");\nconst BOUNDARY_FILL_Y_RE = /[\\s,:;.!?/–—-]*/y;\n\n/**\n * Linear form of `BOUNDARY [\\s,:;.!?/–—-]* TAIL` searched leftmost-first and non-overlapping. Every boundary inside one\n * punctuation/space run reaches the same run end, and a tail never starts inside the run except at a hyphen\n * (where starting at the run end matches whenever starting at the hyphen does), so each run is scanned once.\n * `onMatch` receives the boundary start, the match end and the tail match; return true to stop.\n */\nfunction scanAfterBoundary(\n\ttext: string,\n\ttail: RegExp,\n\tonMatch: (start: number, end: number, tailMatch: RegExpExecArray) => boolean,\n): void {\n\tFOLLOW_UP_BOUNDARY_G_RE.lastIndex = 0;\n\tlet failedRunEnd = -1;\n\tfor (let boundary = FOLLOW_UP_BOUNDARY_G_RE.exec(text); boundary; boundary = FOLLOW_UP_BOUNDARY_G_RE.exec(text)) {\n\t\tif (boundary.index + boundary[0].length <= failedRunEnd) continue;\n\t\tBOUNDARY_FILL_Y_RE.lastIndex = boundary.index + boundary[0].length;\n\t\tBOUNDARY_FILL_Y_RE.exec(text);\n\t\tconst runEnd = BOUNDARY_FILL_Y_RE.lastIndex;\n\t\ttail.lastIndex = runEnd;\n\t\tconst tailMatch = tail.exec(text);\n\t\tif (!tailMatch) {\n\t\t\tfailedRunEnd = runEnd;\n\t\t\tcontinue;\n\t\t}\n\t\tconst end = runEnd + tailMatch[0].length;\n\t\tif (onMatch(boundary.index, end, tailMatch)) return;\n\t\tFOLLOW_UP_BOUNDARY_G_RE.lastIndex = end;\n\t\tfailedRunEnd = -1;\n\t}\n}\n\nfunction hasCoordinatedBoundedEditTarget(target: string): boolean {\n\tconst maskedTarget = maskQuotedText(target);\n\tconst firstBoundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskedTarget);\n\tconst location = BOUNDED_LOCATION_BOUNDARY_RE.exec(maskedTarget);\n\tif (\n\t\tfirstBoundary &&\n\t\tlocation &&\n\t\t(location.index ?? 0) < (firstBoundary.index ?? 0) &&\n\t\tLOCATION_REFERENCE_CONJUNCTION_RE.test(firstBoundary[0]) &&\n\t\tisBoundedEditTarget(maskedTarget.slice(0, location.index).trim(), \"change\")\n\t) {\n\t\treturn false;\n\t}\n\tlet found = false;\n\tscanAfterBoundary(maskedTarget, COORDINATED_BOUNDED_EDIT_TARGET_TAIL_RE, () => {\n\t\tfound = true;\n\t\treturn true;\n\t});\n\treturn found;\n}\n\nfunction hasFollowUpSubstantiveChange(value: string): boolean {\n\tlet found = false;\n\tscanAfterBoundary(maskQuotedText(value), FOLLOW_UP_CHANGE_TAIL_RE, () => {\n\t\tfound = true;\n\t\treturn true;\n\t});\n\treturn found;\n}\n\nfunction isShortLiteralValue(value: string): boolean {\n\tconst trimmed = value.trim();\n\tif (trimmed.length <= 80 && !/[\\r\\n]/.test(trimmed) && isEntireQuotedLiteral(trimmed)) {\n\t\treturn true;\n\t}\n\tif (!isShortBoundedPhrase(trimmed, 8) || hasFollowUpSubstantiveChange(trimmed)) {\n\t\treturn false;\n\t}\n\tconst withoutTerminalPunctuation = trimmed.replace(/[.!?]+$/, \"\").trim();\n\tif (/^(?:[/#@]|https?:\\/\\/)/i.test(withoutTerminalPunctuation)) return true;\n\tif (/^[A-Z0-9]/.test(withoutTerminalPunctuation)) return true;\n\tif (BOUNDED_COPY_CONNECTOR_RE.test(withoutTerminalPunctuation)) return true;\n\treturn !LEADING_SUBSTANTIVE_CHANGE_VALUE_RE.test(trimmed);\n}\n\nfunction isShortLocation(value: string): boolean {\n\treturn (\n\t\tisShortBoundedPhrase(value, 8) &&\n\t\t!hasFollowUpSubstantiveChange(value) &&\n\t\t!BOUNDED_LOCATION_PURPOSE_RE.test(value) &&\n\t\t!FUNCTIONAL_PURPOSE_CLAUSE_RE.test(value)\n\t);\n}\n\n/**\n * Linear form of `^HEAD(.+?)\\s+to\\s+(.+)$` on trimmed input: first separator whose left side and right side hold no line\n * break. The regex's only extra parse (an all-whitespace left side) classifies as not-a-literal, same as no match.\n */\nfunction matchFromTo(value: string, head: RegExp): [string, string] | null {\n\tconst headMatch = head.exec(value);\n\tif (!headMatch) return null;\n\tconst start = headMatch[0].length;\n\tconst relativeBreak = value.slice(start).search(/[\\n\\r\\u2028\\u2029]/);\n\tconst firstBreak = relativeBreak === -1 ? Number.POSITIVE_INFINITY : start + relativeBreak;\n\tconst lastBreak = Math.max(\n\t\tvalue.lastIndexOf(\"\\n\"),\n\t\tvalue.lastIndexOf(\"\\r\"),\n\t\tvalue.lastIndexOf(\"\\u2028\"),\n\t\tvalue.lastIndexOf(\"\\u2029\"),\n\t);\n\tFROM_TO_SEPARATOR_RE.lastIndex = start;\n\tfor (let match = FROM_TO_SEPARATOR_RE.exec(value); match; match = FROM_TO_SEPARATOR_RE.exec(value)) {\n\t\tif (match.index > firstBreak) return null;\n\t\tconst rightStart = match.index + match[0].length;\n\t\tif (lastBreak < rightStart) return [value.slice(start, match.index), value.slice(rightStart)];\n\t\tFROM_TO_SEPARATOR_RE.lastIndex = match.index + 1;\n\t}\n\treturn null;\n}\n\nfunction isBoundedEditTarget(target: string, action?: string | null): boolean {\n\tconst match = BOUNDED_EDIT_TARGET_RE.exec(target);\n\tif (!match) return false;\n\n\tconst modifiers = match[1]?.trim() ?? \"\";\n\tif (\n\t\t(!action || action === \"add\") &&\n\t\tCAPABILITY_CONTAINER_MODIFIER_RE.test(modifiers) &&\n\t\t!BOUNDED_UI_SURFACE_MODIFIER_RE.test(modifiers)\n\t) {\n\t\treturn false;\n\t}\n\n\tconst remainder = match[3]?.trim() ?? \"\";\n\tif (hasFollowUpSubstantiveChange(remainder)) return false;\n\tif (!remainder || /^[.!?]+$/.test(remainder)) return true;\n\tif (BOUNDED_PRESENTATION_ADJECTIVE_RE.test(remainder)) return true;\n\tif (BOUNDED_PASSIVE_REMOVAL_RE.test(remainder)) return true;\n\tif (BOUNDED_PASSIVE_COMPLETED_RE.test(remainder)) return true;\n\n\tconst passiveFromToMatch = matchFromTo(remainder, BOUNDED_PASSIVE_FROM_TO_HEAD_RE);\n\tif (passiveFromToMatch) {\n\t\treturn isShortLiteralValue(passiveFromToMatch[0]) && isShortLiteralValue(passiveFromToMatch[1]);\n\t}\n\n\tconst passiveValueMatch = BOUNDED_PASSIVE_VALUE_RE.exec(remainder);\n\tif (passiveValueMatch) return isShortLiteralValue(passiveValueMatch[1] ?? \"\");\n\n\tconst passivePresentationMatch = BOUNDED_PASSIVE_PRESENTATION_RE.exec(remainder);\n\tif (passivePresentationMatch) {\n\t\treturn BOUNDED_PRESENTATION_ADJECTIVE_RE.test(passivePresentationMatch[1] ?? \"\");\n\t}\n\n\tconst fromToMatch = matchFromTo(remainder, BOUNDED_FROM_TO_HEAD_RE);\n\tif (fromToMatch) return isShortLiteralValue(fromToMatch[0]) && isShortLiteralValue(fromToMatch[1]);\n\n\tconst contentValueMatch = BOUNDED_CONTENT_VALUE_RE.exec(remainder);\n\tif (contentValueMatch) return isShortLiteralValue(contentValueMatch[1] ?? \"\");\n\n\tconst toValueMatch = BOUNDED_TO_VALUE_RE.exec(remainder);\n\tif (toValueMatch) return isShortLiteralValue(toValueMatch[1] ?? \"\");\n\n\tconst presentationPayloadMatch = BOUNDED_PRESENTATION_PAYLOAD_RE.exec(remainder);\n\tif (presentationPayloadMatch) {\n\t\treturn isBoundedEditTarget(presentationPayloadMatch[1] ?? \"\", \"change\");\n\t}\n\n\tconst locationMatch = BOUNDED_LOCATION_RE.exec(remainder);\n\treturn locationMatch ? isShortLocation(locationMatch[1] ?? \"\") : false;\n}\n\nfunction matchDesiredStateRequest(prompt: string): { target: string | null } | null {\n\tfor (const pattern of DESIRED_STATE_REQUEST_RES) {\n\t\tconst match = pattern.exec(prompt);\n\t\tif (match) return { target: match[1]?.trimStart() ?? null };\n\t}\n\treturn null;\n}\n\ntype ChangeRequestKind = \"none\" | \"bounded\" | \"substantive\";\n\nfunction firstChangeClauseTarget(target: string): string {\n\tconst boundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskQuotedText(target));\n\treturn target.slice(0, boundary?.index ?? target.length).trim();\n}\n\nfunction desiredStateContinuation(target: string): string | null {\n\tconst boundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskQuotedText(target));\n\tif (!boundary) return null;\n\treturn target\n\t\t.slice((boundary.index ?? 0) + boundary[0].length)\n\t\t.replace(FOLLOW_UP_PREFIX_RE, \"\")\n\t\t.trim();\n}\n\nfunction isAdvisoryContinuation(target: string): boolean {\n\tif (!target || COURTESY_ONLY_RE.test(target) || ADVISORY_OUTPUT_TARGET_RE.test(target)) {\n\t\treturn true;\n\t}\n\tconst outputRequest = ADVISORY_OUTPUT_REQUEST_RE.exec(target);\n\tif (outputRequest && ADVISORY_OUTPUT_TARGET_RE.test(outputRequest[1] ?? \"\")) return true;\n\treturn LEADING_ADVISORY_REQUEST_RE.test(target);\n}\n\nfunction classifyConjoinedChangeRequest(target: string, options: { advisoryTopic?: boolean } = {}): ChangeRequestKind {\n\tconst maskedTarget = maskQuotedText(target);\n\tconst matches: Array<{ start: number; end: number; action: string }> = [];\n\tscanAfterBoundary(maskedTarget, FOLLOW_UP_CHANGE_TAIL_RE, (start, end, tailMatch) => {\n\t\tmatches.push({ start, end, action: tailMatch[1] ?? \"\" });\n\t\treturn false;\n\t});\n\tlet requestKind: ChangeRequestKind = \"none\";\n\n\tfor (const match of matches) {\n\t\tconst action = match.action.toLowerCase();\n\t\tif (!action) return \"substantive\";\n\n\t\t// Masking a suffix equals the suffix of the masked text: no quote span can cross the action word.\n\t\tconst editStart = match.end + target.slice(match.end).search(/\\S|$/);\n\t\tconst editTarget = target.slice(editStart);\n\t\tconst nextBoundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskedTarget.slice(editStart));\n\t\tconst clauseTarget = editTarget.slice(0, nextBoundary?.index ?? editTarget.length).trim();\n\t\tconst matchedText = maskedTarget.slice(match.start, match.end);\n\t\tif (\n\t\t\toptions.advisoryTopic &&\n\t\t\tADVISORY_TOPIC_COMPOUND_ACTION_RE.test(action) &&\n\t\t\tADVISORY_TOPIC_COMPOUND_HEAD_RE.test(clauseTarget) &&\n\t\t\t!EXPLICIT_FOLLOW_UP_REQUEST_RE.test(matchedText)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (ADVISORY_OUTPUT_ACTIONS.has(action) && ADVISORY_OUTPUT_TARGET_RE.test(clauseTarget)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!POTENTIALLY_BOUNDED_ACTIONS.has(action)) return \"substantive\";\n\t\tif (!isBoundedEditTarget(clauseTarget, action)) return \"substantive\";\n\t\tif (hasCoordinatedBoundedEditTarget(editTarget)) return \"substantive\";\n\t\tif (requestKind === \"bounded\") return \"substantive\";\n\t\trequestKind = \"bounded\";\n\t}\n\n\treturn requestKind;\n}\n\nfunction classifyNonImplementationDesire(target: string): ChangeRequestKind | null {\n\tif (!NON_IMPLEMENTATION_DESIRE_RE.test(target)) return null;\n\n\tconst advisoryTopic = NON_IMPLEMENTATION_TOPIC_RE.test(target);\n\tconst conjoinedRequest = classifyConjoinedChangeRequest(target, { advisoryTopic });\n\tif (conjoinedRequest !== \"none\") return conjoinedRequest;\n\tif (advisoryTopic) return \"none\";\n\n\tconst continuation = desiredStateContinuation(target);\n\treturn continuation && !isAdvisoryContinuation(continuation) ? \"substantive\" : \"none\";\n}\n\nfunction hasNonImplementationDesire(prompt: string): boolean {\n\tconst request = matchDesiredStateRequest(prompt);\n\tif (!request?.target) return false;\n\tconst requestKind = classifyNonImplementationDesire(request.target);\n\treturn requestKind !== null && requestKind !== \"substantive\";\n}\n\nfunction classifyChangeRequest(prompt: string): ChangeRequestKind {\n\tconst match = SUBSTANTIVE_CHANGE_REQUEST_RE.exec(prompt);\n\tif (match) {\n\t\tconst action = match[1]?.toLowerCase();\n\t\tif (!action || !POTENTIALLY_BOUNDED_ACTIONS.has(action)) return \"substantive\";\n\n\t\tconst target = prompt.slice(match[0].length).trimStart();\n\t\tconst conjoinedRequest = classifyConjoinedChangeRequest(prompt);\n\t\tif (!isBoundedEditTarget(firstChangeClauseTarget(target), action)) {\n\t\t\treturn action === \"rename\" && conjoinedRequest === \"none\" && !hasCoordinatedBoundedEditTarget(target)\n\t\t\t\t? \"none\"\n\t\t\t\t: \"substantive\";\n\t\t}\n\t\tif (hasCoordinatedBoundedEditTarget(target)) return \"substantive\";\n\t\treturn conjoinedRequest === \"none\" ? \"bounded\" : \"substantive\";\n\t}\n\n\tif (LEADING_ADVISORY_REQUEST_RE.test(prompt)) {\n\t\tconst conjoinedRequest = classifyConjoinedChangeRequest(prompt);\n\t\tif (conjoinedRequest !== \"none\") return conjoinedRequest;\n\t}\n\n\tconst desiredStateRequest = matchDesiredStateRequest(prompt);\n\tif (!desiredStateRequest) return \"none\";\n\tconst { target } = desiredStateRequest;\n\tif (target) {\n\t\tconst nonImplementationRequest = classifyNonImplementationDesire(target);\n\t\tif (nonImplementationRequest !== null) return nonImplementationRequest;\n\t}\n\treturn target && isBoundedEditTarget(target) ? \"bounded\" : \"substantive\";\n}\n\nfunction resolvePromptExecutionDepth(\n\ttrimmed: string,\n\tsignalText: string,\n\timperativeTotal: number,\n\tchangeRequestKind: ChangeRequestKind,\n): PromptExecutionDepth {\n\tif (!trimmed) return \"quick\";\n\tif (EXPLICIT_THOROUGH_BUILD_RE.test(signalText)) return \"thorough\";\n\tif (HIGH_RISK_BUILD_RE.test(signalText) && (COMPLEX_BUILD_RE.test(signalText) || imperativeTotal >= 2)) {\n\t\treturn \"thorough\";\n\t}\n\tif (signalText.length > 600 && imperativeTotal >= 3) return \"thorough\";\n\tif (hasNonImplementationDesire(trimmed)) return \"quick\";\n\tif (changeRequestKind === \"bounded\") return \"quick\";\n\tif (COMPLEX_BUILD_RE.test(signalText)) return \"balanced\";\n\tif (changeRequestKind === \"substantive\") return \"balanced\";\n\tif (hasNonLatinComplexitySignal(signalText)) return \"balanced\";\n\tif (signalText.length > 180 && imperativeTotal >= 2) return \"balanced\";\n\tif (hasMultiChangePrompt(signalText)) return \"balanced\";\n\treturn \"quick\";\n}\n\n// Independent of the resolved depth: a prompt can carry a risk signal (e.g.\n// a high-risk domain term) even on a turn where the overall heuristic above\n// settles on 'balanced' because no other arm fired. Consumers that gate on\n// risk (e.g. the review pass) rely on that independence rather than\n// re-deriving reasons from `depth`.\nfunction computeRiskReasons(trimmed: string, imperativeTotal: number): RiskReason[] {\n\tconst reasons: RiskReason[] = [];\n\tif (EXPLICIT_THOROUGH_BUILD_RE.test(trimmed)) reasons.push(\"explicit-thorough-request\");\n\tif (HIGH_RISK_BUILD_RE.test(trimmed)) reasons.push(\"high-risk-domain-term\");\n\tif (trimmed.length > 600 && imperativeTotal >= 3) reasons.push(\"long-multi-imperative\");\n\treturn reasons;\n}\n\nexport function classifyPromptLanguageBucket(prompt: string): \"latin\" | \"non-latin\" {\n\treturn NON_LATIN_RE.test(prompt) ? \"non-latin\" : \"latin\";\n}\n\nexport function classifyPromptSignals(input: { prompt: string; mode?: string | null }): UnifiedPromptClassification {\n\tconst trimmed = input.prompt.trim();\n\tconst signalText = maskQuotedText(trimmed);\n\tconst imperativeTotal = imperativeCount(signalText);\n\tconst changeRequestKind = classifyChangeRequest(trimmed);\n\tconst laneResult = classifyLane({\n\t\tprompt: changeRequestKind === \"bounded\" ? signalText : trimmed,\n\t\tmode: input.mode,\n\t});\n\treturn {\n\t\tlane: laneResult.lane,\n\t\tlaneDecisionSource: laneResult.decisionSource,\n\t\tlaneMatchedSignals: laneResult.matchedSignals,\n\t\tdepth: resolvePromptExecutionDepth(trimmed, signalText, imperativeTotal, changeRequestKind),\n\t\triskReasons: computeRiskReasons(signalText, imperativeTotal),\n\t\tpolicyId: UNIFIED_CLASSIFIER_POLICY_ID,\n\t};\n}\n\nexport interface FlowSizeThresholds {\n\tmediumAt: number;\n\tlargeAt: number;\n}\n\n/**\n * Maps a classifier depth to a Flow size: quick -> small, balanced -> medium, thorough -> large.\n * When `thresholds` and a finite numeric `score` are both given, the score decides instead:\n * score >= largeAt -> large, score >= mediumAt -> medium, else small.\n */\nexport function sizeFromDepth(depth: PromptExecutionDepth, thresholds?: FlowSizeThresholds, score?: number): FlowSize {\n\tif (thresholds !== undefined && typeof score === \"number\" && Number.isFinite(score)) {\n\t\tif (score >= thresholds.largeAt) return \"large\";\n\t\treturn score >= thresholds.mediumAt ? \"medium\" : \"small\";\n\t}\n\tif (depth === \"thorough\") return \"large\";\n\treturn depth === \"balanced\" ? \"medium\" : \"small\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flow-sizing.js","sourceRoot":"","sources":["../src/flow-sizing.ts"],"names":[],"mappings":"AA2CA,MAAM,CAAC,MAAM,4BAA4B,GAAG,kBAA2B,CAAC;AAYxE,kFAAkF;AAClF,0EAA0E;AAC1E,wDAAwD;AACxD,MAAM,aAAa,GAClB,yRAAyR,CAAC;AAE3R,MAAM,kBAAkB,GACvB,2NAA2N,CAAC;AAE7N,MAAM,gBAAgB,GACrB,kMAAkM,CAAC;AAEpM,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,kBAAkB,EAAE,WAAW,EAAE,aAAa,EAAE,YAAY,CAAC,CAAC,CAAC;AAErG,uEAAuE;AACvE,MAAM,gBAAgB,GACrB,4YAA4Y,CAAC;AAC9Y,MAAM,0BAA0B,GAC/B,yGAAyG,CAAC;AAC3G,MAAM,kBAAkB,GACvB,yVAAyV,CAAC;AAC3V,MAAM,gCAAgC,GACrC,8MAA8M,CAAC;AAChN,MAAM,8BAA8B,GAAG,GAAG,gCAAgC,0LAA0L,CAAC;AACrQ,MAAM,gCAAgC,GAAG,0EAA0E,CAAC;AACpH,MAAM,4BAA4B,GAAG,IAAI,MAAM,CAAC,gCAAgC,EAAE,GAAG,CAAC,CAAC;AACvF,MAAM,iCAAiC,GAAG,QAAQ,CAAC;AACnD,MAAM,iCAAiC,GAAG,6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AAG,YAAY,CAAC;QAC/B,MAAM,EAAE,iBAAiB,KAAK,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,OAAO;QAC9D,IAAI,EAAE,KAAK,CAAC,IAAI;KAChB,CAAC,CAAC;IACH,OAAO;QACN,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,kBAAkB,EAAE,UAAU,CAAC,cAAc;QAC7C,kBAAkB,EAAE,UAAU,CAAC,cAAc;QAC7C,GAAG,2BAA2B,CAAC,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,iBAAiB,CAAC;QACvF,WAAW,EAAE,kBAAkB,CAAC,UAAU,EAAE,eAAe,CAAC;QAC5D,QAAQ,EAAE,4BAA4B;KACtC,CAAC;AACH,CAAC;AAOD;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,KAA2B,EAAE,UAA+B,EAAE,KAAc;IACzG,IAAI,UAAU,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrF,IAAI,KAAK,IAAI,UAAU,CAAC,OAAO;YAAE,OAAO,OAAO,CAAC;QAChD,OAAO,KAAK,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;IAC1D,CAAC;IACD,IAAI,KAAK,KAAK,UAAU;QAAE,OAAO,OAAO,CAAC;IACzC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;AAClD,CAAC","sourcesContent":["export type IntentLane = \"debug\" | \"mechanical\" | \"creative\" | \"fallback\";\nexport type IntentDecisionSource = \"keyword-classifier\" | \"mode-override\" | \"default\";\nexport type FlowSize = \"small\" | \"medium\" | \"large\";\n\n// One browser-safe classifier for both the build-depth heuristic\n// (apps/web/lib/ai-modes.ts) and the skill/router intent lane\n// (packages/ai/src/intent/classifier.ts). The D1 golden fixture\n// (packages/ai/src/intent/__fixtures__/unified-classifier-golden.json)\n// preserves the pre-refactor behavior; intentional classifier changes are\n// versioned through UNIFIED_CLASSIFIER_POLICY_ID and focused regression tables.\n//\n// This module centralizes IMPLEMENTATION, not INPUTS: depth and skill-lane\n// consumers may still classify different prompt variants (e.g.\n// attachment-enriched vs. base prompt text) than each other. Unifying what\n// text each caller feeds in is out of scope here — that is the deliberately\n// cut 1-exp-A scope, not this task.\n//\n// Moved from Forge packages/ai/src/intent/unified-classifier.ts (single source of\n// truth for the CLI and the web). This module must have NO imports at all: it is\n// browser-safe and dependency-free (enforced by scripts/check-entry-graphs.mjs).\n\nexport type RiskReason =\n\t| \"explicit-thorough-request\" // EXPLICIT_THOROUGH_BUILD_RE\n\t| \"high-risk-domain-term\" // HIGH_RISK_BUILD_RE\n\t| \"long-multi-imperative\"; // >600 chars + >=3 imperatives\n\nexport type PromptExecutionDepth = \"quick\" | \"balanced\" | \"thorough\";\n\nexport type PromptDepthReason =\n\t| \"empty-prompt\"\n\t| \"explicit-thorough-request\"\n\t| \"high-risk-complexity\"\n\t| \"long-multi-imperative\"\n\t| \"non-implementation-desire\"\n\t| \"bounded-edit\"\n\t| \"hello-world-starter\"\n\t| \"complexity-signal\"\n\t| \"substantive-change\"\n\t| \"non-latin-complexity\"\n\t| \"long-multi-change\"\n\t| \"multi-change\"\n\t| \"default-quick\";\n\nexport const UNIFIED_CLASSIFIER_POLICY_ID = \"unified-regex-v5\" as const;\n\nexport interface UnifiedPromptClassification {\n\tlane: IntentLane;\n\tlaneDecisionSource: IntentDecisionSource;\n\tlaneMatchedSignals: string[];\n\tdepth: PromptExecutionDepth;\n\tdepthReason: PromptDepthReason;\n\triskReasons: RiskReason[];\n\tpolicyId: typeof UNIFIED_CLASSIFIER_POLICY_ID;\n}\n\n// ─── Lane signals (moved verbatim from packages/ai/src/intent/classifier.ts) ───\n// Lane order mirrors the router lane rubric: DEBUG is checked first, then\n// MECHANICAL, then CREATIVE; FALLBACK catches the rest.\nconst DEBUG_SIGNALS =\n\t/\\b(404|500|broken|bug|crash(?:es|ed|ing)?|debug(?:s|ged|ging)?|diagnos(?:e|es|ed|ing)|doesn'?t work|error|exception|fail(?:s|ed|ing)?|failing|flaky|null|not working|regression|root cause|stack trace|troubleshoot(?:s|ed|ing)?|undefined|unexpected|wrong (?:output|result|value))\\b/i;\n\nconst MECHANICAL_SIGNALS =\n\t/\\b(alphabetize|async\\/await|bump|comment out|convert|delete unused|explain|extract (?:component|function)|inline|move (?:file|folder|component)|re-?format|re-?order|remove unused|rename|sort imports|typo|uncomment)\\b/i;\n\nconst CREATIVE_SIGNALS =\n\t/\\b(add|build|component|create|dashboard|design|enhance|feature|flow|generate|implement|improve|integrate|interface|landing|new|page|portal|redesign|screen|section|tool|view|widget|workflow)\\b/i;\n\nconst NAMED_MODE_OVERRIDES = new Set([\"production-ready\", \"add-tests\", \"code-review\", \"create-prd\"]);\n\n// ─── Depth signals (moved verbatim from apps/web/lib/ai-modes.ts) ───\nconst COMPLEX_BUILD_RE =\n\t/\\b(admin|analytics|api|auth|authentication|authorization|backend|calendar|charts?|crud|dashboard|database|deploy|deployment|e2e|end[-\\s]?to[-\\s]?end|full[-\\s]?stack|integration|kanban|multi[-\\s]?(?:page|section|service)|(?:[2-9]|[1-9]\\d+|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|multiple|several)\\s+sections|permissions?|production|reports?|roles?|security|tests?|workflow)\\b/i;\nconst EXPLICIT_THOROUGH_BUILD_RE =\n\t/\\b(use\\s+opus|opus[-\\s]?level|thorough|deep(?:est)?\\s+reasoning|deep\\s+review|architecture\\s+review)\\b/i;\nconst HIGH_RISK_BUILD_RE =\n\t/\\b(threat\\s+model|security\\s+review|compliance|regulated|hipaa|soc\\s*2|gdpr|pci|data\\s+retention|data\\s+migration|schema\\s+migration|migrat(?:e|es|ed|ing)\\s+(?:(?:the|a|an|our|your)\\s+)?database\\s+schema|tenant\\s+isolation|multi[-\\s]?tenant\\s+authorization|authorization\\s+architecture|incident\\s+recovery|rollback\\s+plan|payments?|billing)\\b/i;\nconst SUBSTANTIVE_CHANGE_ACTION_SOURCE =\n\t\"add|build|change|connect|configure|create|design|develop|enable|enhance|extend|fix|generate|implement|improve|integrate|introduce|make|redesign|refactor|remove|rename|replace|set\\\\s+up|support|update|wire\";\nconst FOLLOW_UP_CHANGE_ACTION_SOURCE = `${SUBSTANTIVE_CHANGE_ACTION_SOURCE}|allow|automate|calculate|delete|display|export|give|handle|hide|import|invite|launch|let|localize|manage|move|permit|process|provide|rename|search|share|show|sync|track|trigger|unlock`;\nconst FOLLOW_UP_CHANGE_BOUNDARY_SOURCE = \"(?:\\\\b(?:and|also|plus|additionally|then)\\\\b|[,;:.!?]|\\\\s(?:/|-|–|—)\\\\s)\";\nconst FOLLOW_UP_CHANGE_BOUNDARY_RE = new RegExp(FOLLOW_UP_CHANGE_BOUNDARY_SOURCE, \"i\");\nconst LOCATION_REFERENCE_CONJUNCTION_RE = /^and$/i;\nconst REQUEST_DISCOURSE_MODIFIER_SOURCE = \"(?:(?:just|kindly|only|please|simply)\\\\s+)*\";\n// Regex hardening (linear time): adjacent modifier runs are merged because `M* M*` is ambiguous, and\n// `\\s+.+\\s+TAIL` spans use `spacedSpan` below. Every rewrite keeps the original language; see test/flow-sizing.test.ts.\nconst LINE_TERMINATORS = \"\\\\n\\\\r\\\\u2028\\\\u2029\";\n/**\n * Linear form of `\\s+.+\\s+TAIL` where TAIL starts with a non-space and `.` excludes line terminators: either the\n * span starts and ends on non-space characters (the whitespace runs absorb everything else), or it is a single\n * horizontal space inside one whitespace run.\n */\nconst spacedSpan = (tail: string) =>\n\t`(?:\\\\s+\\\\S(?:[^${LINE_TERMINATORS}]*\\\\S)?\\\\s+|\\\\s[${LINE_TERMINATORS}]*[^\\\\S${LINE_TERMINATORS}]\\\\s+)${tail}`;\nconst SUBSTANTIVE_CHANGE_REQUEST_RE = new RegExp(\n\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:(?:(?:can|could|should|would|will)\\\\s+(?:you|we)\\\\s+|(?:i|we)(?:['’]d| would)?\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like(?:\\\\s+you)?\\\\s+to\\\\s+|i\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}want(?:\\\\s+you)?\\\\s+to\\\\s+|we\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:need(?:\\\\s+you)?\\\\s+to|should|must)\\\\s+|let['’]?s\\\\s+)${REQUEST_DISCOURSE_MODIFIER_SOURCE})?(${SUBSTANTIVE_CHANGE_ACTION_SOURCE})\\\\b`,\n\t\"i\",\n);\n// Check the raw entire target, not quote-masked text: a quoted suffix must not disappear into the starter exception.\nconst HELLO_WORLD_STARTER_ACTION_RE = /^(?:build|create|develop|generate|implement|make)$/i;\nconst HELLO_WORLD_STARTER_TARGET_RE =\n\t/^(?:(?:a|an|the)\\s+)?(?:(?:basic|minimal|simple)\\s+)?hello[-\\s]+world(?:\\s+(?:app|application|demo|example|page|program|starter))?[.!?]*$/i;\nconst DESIRED_STATE_REQUEST_RES = [\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:i|we)(?:['’]d\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like|\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:want|need|would\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}like))\\\\s+(?=\\\\S)(.+)$`,\n\t\t\"i\",\n\t),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}can\\\\s+(?:we|you)\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE}have\\\\s+(?=\\\\S)(.+)$`,\n\t\t\"i\",\n\t),\n\tnew RegExp(`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:allow|enable|let)${spacedSpan(\"to\\\\b\")}`, \"i\"),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:give|provide)${spacedSpan(\"(?:a\\\\s+way|the\\\\s+ability)\\\\s+to\\\\b\")}`,\n\t\t\"i\",\n\t),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?!i\\\\b|we\\\\b|you\\\\b)(?:[\\\\w-]+\\\\s+){1,5}(?:should|must|need(?:s)?\\\\s+to)\\\\s+be\\\\s+able\\\\s+to\\\\b`,\n\t\t\"i\",\n\t),\n\tnew RegExp(\n\t\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:a|an|the)${spacedSpan(\"(?:should|must|need(?:s)?\\\\s+to)\\\\s+(?:be\\\\s+(?:added|built|created|implemented|integrated|introduced|supported)\\\\b|(?:allow|enable|have|include|provide|support)\\\\b)\")}`,\n\t\t\"i\",\n\t),\n] as const;\nconst NON_IMPLEMENTATION_DESIRE_BOUNDARY_SOURCE =\n\t\"(?=[.!?]*$|\\\\s+(?:about|of|on|regarding|whether)\\\\b|\\\\s*(?:[,;:]|\\\\b(?:and|also|plus|additionally|then)\\\\b)|\\\\s+(?:-|–|—)\\\\s+)\";\nconst NON_IMPLEMENTATION_DESIRE_RE = new RegExp(\n\t`^(?:to\\\\s+(?:consider|decide|discuss|explore|know|learn|review|understand|wonder)\\\\b|help\\\\s+(?:with\\\\s+)?(?:considering|deciding|discussing|exploring|learning|reviewing|understanding)\\\\b|(?:advice|feedback)${NON_IMPLEMENTATION_DESIRE_BOUNDARY_SOURCE}|(?:a|an|the)\\\\s+(?:analysis|conversation|discussion|explanation|overview|review|summary)${NON_IMPLEMENTATION_DESIRE_BOUNDARY_SOURCE})`,\n\t\"i\",\n);\nconst NON_IMPLEMENTATION_TOPIC_RE =\n\t/^(?:(?:advice|feedback)|(?:a|an|the)\\s+(?:analysis|conversation|discussion|explanation|overview|review|summary))\\s+(?:about|of|on|regarding|whether)\\b/i;\nconst LEADING_ADVISORY_REQUEST_RE = new RegExp(\n\t`^${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:(?:can|could|would|will)\\\\s+(?:you|we)\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE})?(?:analy[sz]e|assess|describe|discuss|explain|explore|review|summarize|tell\\\\s+(?:me|us)|walk\\\\s+(?:me|us)\\\\s+through|give\\\\s+(?:me|us)\\\\s+(?:advice|feedback)|provide\\\\s+(?:me|us)\\\\s+(?:advice|feedback)|help\\\\s+(?:me|us)\\\\s+understand)\\\\b`,\n\t\"i\",\n);\nconst ADVISORY_OUTPUT_ACTIONS = new Set([\"give\", \"provide\", \"show\"]);\nconst ADVISORY_TOPIC_COMPOUND_ACTION_RE =\n\t/^(?:build|change|create|design|export|import|process|search|support|update)$/;\nconst ADVISORY_TOPIC_COMPOUND_HEAD_RE =\n\t/^(?:approach|architecture|consistency|conventions?|coverage|experience|flows?|governance|management|patterns?|performance|process(?:es)?|quality|reliability|security|standards?|strategy|structure|tooling|usability|workflows?)\\b/i;\nconst EXPLICIT_FOLLOW_UP_REQUEST_RE =\n\t/\\b(?:just|kindly|only|please|simply|then)\\b|[;:]|(?:can|could|would|will)\\s+(?:you|we)\\b/i;\nconst ADVISORY_OUTPUT_TARGET_RE =\n\t/^(?:(?:me|us)\\s+)?(?:(?:a|an|more|some|the|your)\\s+)?(?:(?:advice|analysis|assessment|conversation|discussion|explanation|feedback|findings?|next\\s+steps|options?|overview|recommendations?|review|suggestions?|summary|thoughts?|trade[-\\s]?offs?)(?:\\s+(?:about|of|on|regarding)\\s+(?=\\S).+)?|(?:how|what|whether|why)\\b.+)$/i;\nconst ADVISORY_OUTPUT_REQUEST_RE = /^(?:give|provide|show)\\s+(?=\\S)(.+)$/i;\nconst FOLLOW_UP_PREFIX_RE =\n\t/^[\\s,:;.!?/–—-]*(?:(?:and|also|plus|additionally|then)\\b[\\s,:;.!?/–—-]*)*(?:(?:just|kindly|only|please|simply)\\s+)*/i;\nconst COURTESY_ONLY_RE = /^(?:please|thanks|thank\\s+you)[.!?]*$/i;\n// Tail of a follow-up change clause, matched (sticky) where the punctuation/space run after a boundary ends.\nconst FOLLOW_UP_CHANGE_TAIL_RE = new RegExp(\n\t`${REQUEST_DISCOURSE_MODIFIER_SOURCE}(?:(?:can|could|would|will)\\\\s+(?:you|we)\\\\s+${REQUEST_DISCOURSE_MODIFIER_SOURCE})?(${FOLLOW_UP_CHANGE_ACTION_SOURCE})\\\\b(?=\\\\s+\\\\S)`,\n\t\"iy\",\n);\nconst LEADING_SUBSTANTIVE_CHANGE_VALUE_RE = new RegExp(`^(?:${FOLLOW_UP_CHANGE_ACTION_SOURCE})\\\\b\\\\s+\\\\S+`, \"i\");\nconst BOUNDED_COPY_CONNECTOR_RE = /\\b(?:and|by|or)\\b/i;\nconst BOUNDED_LOCATION_PURPOSE_RE = new RegExp(\n\t`\\\\b(?:in\\\\s+order\\\\s+)?to\\\\s+(?:${FOLLOW_UP_CHANGE_ACTION_SOURCE})\\\\b`,\n\t\"i\",\n);\nconst FUNCTIONAL_PURPOSE_CLAUSE_RE =\n\t/\\b(?:so(?:\\s+that)?\\s+\\S+(?:\\s+\\S+){0,2}\\s+(?:can|could|may|might|will|would)\\s+\\S+|that\\s+(?:allows?|enables?|lets?)\\s+\\S+\\s+\\S+|for\\s+\\S+(?:\\s+\\S+){0,2}\\s+to\\s+\\S+)\\b/i;\nconst POTENTIALLY_BOUNDED_ACTIONS = new Set([\n\t\"add\",\n\t\"change\",\n\t\"fix\",\n\t\"improve\",\n\t\"make\",\n\t\"remove\",\n\t\"rename\",\n\t\"replace\",\n\t\"update\",\n]);\nconst BOUNDED_EDIT_TARGET_SOURCE =\n\t\"alignment|border|caption|colou?r|copy|description|font|gap|heading|icon|label|link|margin|padding|placeholder|punctuation|radius|shadow|size|spacing|subtitle|text|title|tooltip|typo|weight|wording\";\nconst BOUNDED_EDIT_TARGET_RE = new RegExp(\n\t`^(?:(?:the|a|an)\\\\s+)?((?:[\\\\w-]+\\\\s+){0,5})(${BOUNDED_EDIT_TARGET_SOURCE})\\\\b(.*)$`,\n\t\"i\",\n);\nconst COORDINATED_BOUNDED_EDIT_TARGET_TAIL_RE = new RegExp(\n\t`(?:(?:and|also|plus|additionally)\\\\s+)?(?:(?:the|a|an)\\\\s+)?(?:[\\\\w-]+\\\\s+){0,5}(?:${BOUNDED_EDIT_TARGET_SOURCE})\\\\b`,\n\t\"iy\",\n);\nconst BOUNDED_UI_SURFACE_MODIFIER_RE =\n\t/\\b(app|application|badge|banner|breadcrumb|button|card|chip|control|dialog|drawer|dropdown|field|footer|form|header|hero|input|list|logo|menu|modal|nav|navbar|navigation|page|panel|popover|row|screen|search|section|select|shell|sidebar|switch|tab|table|tile|toast|toggle|toolbar)\\b/i;\nconst CAPABILITY_CONTAINER_MODIFIER_RE =\n\t/\\b(assistant|builder|center|editor|engine|feature|flow|integration|manager|module|platform|service|system|tool|workflow)\\b/i;\nconst BOUNDED_PRESENTATION_ADJECTIVE_RE =\n\t/^(?:(?:a\\s+(?:bit|little)|much|slightly)\\s+)?(?:bolder|brighter|clearer|cooler|darker|friendlier|larger|lighter|longer|looser|rounder|sharper|shorter|smaller|softer|stronger|thicker|thinner|tighter|warmer|weaker|more\\s+(?:compact|concise|descriptive|prominent|readable|specific|visible))[.!?]*$/i;\nconst BOUNDED_LOCATION_RE =\n\t/^(?:after|around|at|before|below|beside|between|by|in|inside|near|next\\s+to|on|outside|right\\s+next\\s+to|under|within)\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_LOCATION_BOUNDARY_RE =\n\t/\\b(?:after|around|at|before|below|beside|between|by|in|inside|near|next\\s+to|on|outside|right\\s+next\\s+to|under|within)\\s+/i;\nconst BOUNDED_CONTENT_VALUE_RE = /^(?:read|say)\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_TO_VALUE_RE = /^to\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_FROM_TO_HEAD_RE = /^from\\s+(?=\\S)/i;\nconst BOUNDED_PRESENTATION_PAYLOAD_RE = /^with\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_PASSIVE_VALUE_RE = /^(?:changed|fixed|renamed|replaced|set|updated)\\s+(?:to|with)\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_PASSIVE_FROM_TO_HEAD_RE = /^(?:changed|renamed|replaced|updated)\\s+from\\s+(?=\\S)/i;\nconst FROM_TO_SEPARATOR_RE = /(?<=\\S)\\s+to\\s+(?=\\S)/gi;\nconst BOUNDED_PASSIVE_COMPLETED_RE = /^(?:changed|fixed|renamed|replaced|set|updated)[.!?]*$/i;\nconst BOUNDED_PASSIVE_PRESENTATION_RE = /^made\\s+(?=\\S)(.+)$/i;\nconst BOUNDED_PASSIVE_REMOVAL_RE = /^(?:deleted|removed)[.!?]*$/i;\nconst BUILD_CONJUNCTION_RE = /\\b(and|also|plus|additionally)\\b/i;\nconst LIST_SEPARATOR_RE = /[,;،]/u;\nconst NON_LATIN_RE = /[^\\p{Script=Latin}\\p{Script=Common}\\p{Script=Inherited}]/u;\nconst ARABIC_COMPLEX_BUILD_RE = /(اختبارات|إعدادات|بيانات|تقارير|تحكم|صلاحيات|لوحة)/u;\nconst BUILD_IMPERATIVE_RES = [\n\t\"build\",\n\t\"create\",\n\t\"generate\",\n\t\"change\",\n\t\"make\",\n\t\"add\",\n\t\"remove\",\n\t\"delete\",\n\t\"update\",\n\t\"move\",\n\t\"replace\",\n\t\"fix\",\n\t\"implement\",\n\t\"wire\",\n].map((value) => new RegExp(`\\\\b${value}\\\\b`, \"gi\"));\n\nfunction matchSignals(prompt: string, pattern: RegExp): string[] {\n\tconst global = new RegExp(pattern.source, \"gi\");\n\treturn Array.from(new Set(Array.from(prompt.matchAll(global), (match) => match[0].toLowerCase())));\n}\n\ninterface LaneResult {\n\tlane: IntentLane;\n\tdecisionSource: IntentDecisionSource;\n\tmatchedSignals: string[];\n}\n\nfunction classifyLane(input: { prompt: string; mode?: string | null }): LaneResult {\n\tconst namedMode = input.mode?.trim();\n\tif (namedMode && NAMED_MODE_OVERRIDES.has(namedMode)) {\n\t\treturn {\n\t\t\tlane: \"creative\",\n\t\t\tdecisionSource: \"mode-override\",\n\t\t\tmatchedSignals: [`mode:${namedMode}`],\n\t\t};\n\t}\n\n\tconst prompt = input.prompt.trim();\n\tif (!prompt) return { lane: \"fallback\", decisionSource: \"default\", matchedSignals: [] };\n\n\tconst lanes: Array<{ lane: IntentLane; pattern: RegExp }> = [\n\t\t{ lane: \"debug\", pattern: DEBUG_SIGNALS },\n\t\t{ lane: \"mechanical\", pattern: MECHANICAL_SIGNALS },\n\t\t{ lane: \"creative\", pattern: CREATIVE_SIGNALS },\n\t];\n\tfor (const { lane, pattern } of lanes) {\n\t\tconst matchedSignals = matchSignals(prompt, pattern);\n\t\tif (matchedSignals.length > 0) {\n\t\t\treturn { lane, decisionSource: \"keyword-classifier\", matchedSignals };\n\t\t}\n\t}\n\treturn { lane: \"fallback\", decisionSource: \"default\", matchedSignals: [] };\n}\n\nfunction imperativeCount(prompt: string): number {\n\treturn BUILD_IMPERATIVE_RES.reduce((count, re) => {\n\t\tconst matches = prompt.match(re);\n\t\treturn count + (matches?.length ?? 0);\n\t}, 0);\n}\n\nfunction hasMultiChangePrompt(prompt: string): boolean {\n\tif (!BUILD_CONJUNCTION_RE.test(prompt)) return false;\n\treturn imperativeCount(prompt) >= 2;\n}\n\nfunction hasNonLatinComplexitySignal(prompt: string): boolean {\n\tif (!NON_LATIN_RE.test(prompt)) return false;\n\tif (ARABIC_COMPLEX_BUILD_RE.test(prompt)) return true;\n\treturn LIST_SEPARATOR_RE.test(prompt) && prompt.length > 48;\n}\n\nfunction isShortBoundedPhrase(value: string, maxWords: number): boolean {\n\tconst trimmed = value.trim();\n\tif (!trimmed || trimmed.length > 80 || /[\\r\\n;]/.test(trimmed)) return false;\n\tconst withoutTerminalPunctuation = trimmed.replace(/[.!?]+$/, \"\").trim();\n\tif (!withoutTerminalPunctuation || /[.!?]\\s/.test(withoutTerminalPunctuation)) return false;\n\treturn withoutTerminalPunctuation.split(/\\s+/).length <= maxWords;\n}\n\nconst QUOTE_PAIRS: Readonly<Record<string, string>> = {\n\t'\"': '\"',\n\t\"'\": \"'\",\n\t\"`\": \"`\",\n\t\"“\": \"”\",\n\t\"‘\": \"’\",\n};\n\nfunction isWordCharacterAt(value: string, index: number): boolean {\n\tconst character = value[index];\n\treturn character !== undefined && /[\\p{L}\\p{N}_]/u.test(character);\n}\n\nfunction maskQuotedText(value: string): string {\n\tconst masked = value.split(\"\");\n\t// An opener whose scan found no closer before the end of its line proves every later opener of the same\n\t// kind on that line also fails (closer validity does not depend on the opener), so it is skipped.\n\tconst noCloserBefore = new Map<string, number>();\n\n\tfor (let openingIndex = 0; openingIndex < value.length; openingIndex += 1) {\n\t\tconst opening = value[openingIndex] ?? \"\";\n\t\tconst closing = QUOTE_PAIRS[opening];\n\t\tif (!closing) continue;\n\n\t\tconst isSingleQuote = opening === \"'\" || opening === \"‘\";\n\t\tif (\n\t\t\tisSingleQuote &&\n\t\t\t(isWordCharacterAt(value, openingIndex - 1) ||\n\t\t\t\t!value[openingIndex + 1] ||\n\t\t\t\t/[\\s\\r\\n]/.test(value[openingIndex + 1] ?? \"\"))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((noCloserBefore.get(opening) ?? -1) > openingIndex) continue;\n\n\t\tlet closingIndex = openingIndex + 1;\n\t\tfor (; closingIndex < value.length; closingIndex += 1) {\n\t\t\tconst character = value[closingIndex];\n\t\t\tif (character === \"\\r\" || character === \"\\n\") break;\n\t\t\tif (character !== closing) continue;\n\t\t\tif (\n\t\t\t\tisSingleQuote &&\n\t\t\t\tisWordCharacterAt(value, closingIndex - 1) &&\n\t\t\t\tisWordCharacterAt(value, closingIndex + 1)\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (let index = openingIndex; index <= closingIndex; index += 1) {\n\t\t\t\tmasked[index] = \" \";\n\t\t\t}\n\t\t\topeningIndex = closingIndex;\n\t\t\tbreak;\n\t\t}\n\t\tif (closingIndex >= value.length || value[closingIndex] === \"\\r\" || value[closingIndex] === \"\\n\") {\n\t\t\tnoCloserBefore.set(opening, closingIndex);\n\t\t}\n\t}\n\n\treturn masked.join(\"\");\n}\n\nfunction isEntireQuotedLiteral(value: string): boolean {\n\tconst trimmed = value.trim();\n\tconst opening = trimmed[0] ?? \"\";\n\tconst closing = QUOTE_PAIRS[opening];\n\treturn Boolean(closing && trimmed.length >= 2 && trimmed.at(-1) === closing);\n}\n\nconst FOLLOW_UP_BOUNDARY_G_RE = new RegExp(FOLLOW_UP_CHANGE_BOUNDARY_SOURCE, \"gi\");\nconst BOUNDARY_FILL_Y_RE = /[\\s,:;.!?/–—-]*/y;\n\n/**\n * Linear form of `BOUNDARY [\\s,:;.!?/–—-]* TAIL` searched leftmost-first and non-overlapping. Every boundary inside one\n * punctuation/space run reaches the same run end, and a tail never starts inside the run except at a hyphen\n * (where starting at the run end matches whenever starting at the hyphen does), so each run is scanned once.\n * `onMatch` receives the boundary start, the match end and the tail match; return true to stop.\n */\nfunction scanAfterBoundary(\n\ttext: string,\n\ttail: RegExp,\n\tonMatch: (start: number, end: number, tailMatch: RegExpExecArray) => boolean,\n): void {\n\tFOLLOW_UP_BOUNDARY_G_RE.lastIndex = 0;\n\tlet failedRunEnd = -1;\n\tfor (let boundary = FOLLOW_UP_BOUNDARY_G_RE.exec(text); boundary; boundary = FOLLOW_UP_BOUNDARY_G_RE.exec(text)) {\n\t\tif (boundary.index + boundary[0].length <= failedRunEnd) continue;\n\t\tBOUNDARY_FILL_Y_RE.lastIndex = boundary.index + boundary[0].length;\n\t\tBOUNDARY_FILL_Y_RE.exec(text);\n\t\tconst runEnd = BOUNDARY_FILL_Y_RE.lastIndex;\n\t\ttail.lastIndex = runEnd;\n\t\tconst tailMatch = tail.exec(text);\n\t\tif (!tailMatch) {\n\t\t\tfailedRunEnd = runEnd;\n\t\t\tcontinue;\n\t\t}\n\t\tconst end = runEnd + tailMatch[0].length;\n\t\tif (onMatch(boundary.index, end, tailMatch)) return;\n\t\tFOLLOW_UP_BOUNDARY_G_RE.lastIndex = end;\n\t\tfailedRunEnd = -1;\n\t}\n}\n\nfunction hasCoordinatedBoundedEditTarget(target: string): boolean {\n\tconst maskedTarget = maskQuotedText(target);\n\tconst firstBoundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskedTarget);\n\tconst location = BOUNDED_LOCATION_BOUNDARY_RE.exec(maskedTarget);\n\tif (\n\t\tfirstBoundary &&\n\t\tlocation &&\n\t\t(location.index ?? 0) < (firstBoundary.index ?? 0) &&\n\t\tLOCATION_REFERENCE_CONJUNCTION_RE.test(firstBoundary[0]) &&\n\t\tisBoundedEditTarget(maskedTarget.slice(0, location.index).trim(), \"change\")\n\t) {\n\t\treturn false;\n\t}\n\tlet found = false;\n\tscanAfterBoundary(maskedTarget, COORDINATED_BOUNDED_EDIT_TARGET_TAIL_RE, () => {\n\t\tfound = true;\n\t\treturn true;\n\t});\n\treturn found;\n}\n\nfunction hasFollowUpSubstantiveChange(value: string): boolean {\n\tlet found = false;\n\tscanAfterBoundary(maskQuotedText(value), FOLLOW_UP_CHANGE_TAIL_RE, () => {\n\t\tfound = true;\n\t\treturn true;\n\t});\n\treturn found;\n}\n\nfunction isShortLiteralValue(value: string): boolean {\n\tconst trimmed = value.trim();\n\tif (trimmed.length <= 80 && !/[\\r\\n]/.test(trimmed) && isEntireQuotedLiteral(trimmed)) {\n\t\treturn true;\n\t}\n\tif (!isShortBoundedPhrase(trimmed, 8) || hasFollowUpSubstantiveChange(trimmed)) {\n\t\treturn false;\n\t}\n\tconst withoutTerminalPunctuation = trimmed.replace(/[.!?]+$/, \"\").trim();\n\tif (/^(?:[/#@]|https?:\\/\\/)/i.test(withoutTerminalPunctuation)) return true;\n\tif (/^[A-Z0-9]/.test(withoutTerminalPunctuation)) return true;\n\tif (BOUNDED_COPY_CONNECTOR_RE.test(withoutTerminalPunctuation)) return true;\n\treturn !LEADING_SUBSTANTIVE_CHANGE_VALUE_RE.test(trimmed);\n}\n\nfunction isShortLocation(value: string): boolean {\n\treturn (\n\t\tisShortBoundedPhrase(value, 8) &&\n\t\t!hasFollowUpSubstantiveChange(value) &&\n\t\t!BOUNDED_LOCATION_PURPOSE_RE.test(value) &&\n\t\t!FUNCTIONAL_PURPOSE_CLAUSE_RE.test(value)\n\t);\n}\n\n/**\n * Linear form of `^HEAD(.+?)\\s+to\\s+(.+)$` on trimmed input: first separator whose left side and right side hold no line\n * break. The regex's only extra parse (an all-whitespace left side) classifies as not-a-literal, same as no match.\n */\nfunction matchFromTo(value: string, head: RegExp): [string, string] | null {\n\tconst headMatch = head.exec(value);\n\tif (!headMatch) return null;\n\tconst start = headMatch[0].length;\n\tconst relativeBreak = value.slice(start).search(/[\\n\\r\\u2028\\u2029]/);\n\tconst firstBreak = relativeBreak === -1 ? Number.POSITIVE_INFINITY : start + relativeBreak;\n\tconst lastBreak = Math.max(\n\t\tvalue.lastIndexOf(\"\\n\"),\n\t\tvalue.lastIndexOf(\"\\r\"),\n\t\tvalue.lastIndexOf(\"\\u2028\"),\n\t\tvalue.lastIndexOf(\"\\u2029\"),\n\t);\n\tFROM_TO_SEPARATOR_RE.lastIndex = start;\n\tfor (let match = FROM_TO_SEPARATOR_RE.exec(value); match; match = FROM_TO_SEPARATOR_RE.exec(value)) {\n\t\tif (match.index > firstBreak) return null;\n\t\tconst rightStart = match.index + match[0].length;\n\t\tif (lastBreak < rightStart) return [value.slice(start, match.index), value.slice(rightStart)];\n\t\tFROM_TO_SEPARATOR_RE.lastIndex = match.index + 1;\n\t}\n\treturn null;\n}\n\nfunction isBoundedEditTarget(target: string, action?: string | null): boolean {\n\tconst match = BOUNDED_EDIT_TARGET_RE.exec(target);\n\tif (!match) return false;\n\n\tconst modifiers = match[1]?.trim() ?? \"\";\n\tif (BOUNDED_LOCATION_PURPOSE_RE.test(modifiers) || FUNCTIONAL_PURPOSE_CLAUSE_RE.test(modifiers)) return false;\n\tif (\n\t\t(!action || action === \"add\") &&\n\t\tCAPABILITY_CONTAINER_MODIFIER_RE.test(modifiers) &&\n\t\t!BOUNDED_UI_SURFACE_MODIFIER_RE.test(modifiers)\n\t) {\n\t\treturn false;\n\t}\n\n\tconst remainder = match[3]?.trim() ?? \"\";\n\tif (hasFollowUpSubstantiveChange(remainder)) return false;\n\tif (!remainder || /^[.!?]+$/.test(remainder)) return true;\n\tif (BOUNDED_PRESENTATION_ADJECTIVE_RE.test(remainder)) return true;\n\tif (BOUNDED_PASSIVE_REMOVAL_RE.test(remainder)) return true;\n\tif (BOUNDED_PASSIVE_COMPLETED_RE.test(remainder)) return true;\n\n\tconst passiveFromToMatch = matchFromTo(remainder, BOUNDED_PASSIVE_FROM_TO_HEAD_RE);\n\tif (passiveFromToMatch) {\n\t\treturn isShortLiteralValue(passiveFromToMatch[0]) && isShortLiteralValue(passiveFromToMatch[1]);\n\t}\n\n\tconst passiveValueMatch = BOUNDED_PASSIVE_VALUE_RE.exec(remainder);\n\tif (passiveValueMatch) return isShortLiteralValue(passiveValueMatch[1] ?? \"\");\n\n\tconst passivePresentationMatch = BOUNDED_PASSIVE_PRESENTATION_RE.exec(remainder);\n\tif (passivePresentationMatch) {\n\t\treturn BOUNDED_PRESENTATION_ADJECTIVE_RE.test(passivePresentationMatch[1] ?? \"\");\n\t}\n\n\tconst fromToMatch = matchFromTo(remainder, BOUNDED_FROM_TO_HEAD_RE);\n\tif (fromToMatch) return isShortLiteralValue(fromToMatch[0]) && isShortLiteralValue(fromToMatch[1]);\n\n\tconst contentValueMatch = BOUNDED_CONTENT_VALUE_RE.exec(remainder);\n\tif (contentValueMatch) return isShortLiteralValue(contentValueMatch[1] ?? \"\");\n\n\tconst toValueMatch = BOUNDED_TO_VALUE_RE.exec(remainder);\n\tif (toValueMatch) return isShortLiteralValue(toValueMatch[1] ?? \"\");\n\n\tconst presentationPayloadMatch = BOUNDED_PRESENTATION_PAYLOAD_RE.exec(remainder);\n\tif (presentationPayloadMatch) {\n\t\treturn isBoundedEditTarget(presentationPayloadMatch[1] ?? \"\", \"change\");\n\t}\n\n\tconst locationMatch = BOUNDED_LOCATION_RE.exec(remainder);\n\treturn locationMatch ? isShortLocation(locationMatch[1] ?? \"\") : false;\n}\n\nfunction matchDesiredStateRequest(prompt: string): { target: string | null } | null {\n\tfor (const pattern of DESIRED_STATE_REQUEST_RES) {\n\t\tconst match = pattern.exec(prompt);\n\t\tif (match) return { target: match[1]?.trimStart() ?? null };\n\t}\n\treturn null;\n}\n\ntype ChangeRequestKind = \"none\" | \"bounded\" | \"substantive\";\n\nfunction firstChangeClauseTarget(target: string): string {\n\tconst boundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskQuotedText(target));\n\treturn target.slice(0, boundary?.index ?? target.length).trim();\n}\n\nfunction desiredStateContinuation(target: string): string | null {\n\tconst boundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskQuotedText(target));\n\tif (!boundary) return null;\n\treturn target\n\t\t.slice((boundary.index ?? 0) + boundary[0].length)\n\t\t.replace(FOLLOW_UP_PREFIX_RE, \"\")\n\t\t.trim();\n}\n\nfunction isAdvisoryContinuation(target: string): boolean {\n\tif (!target || COURTESY_ONLY_RE.test(target) || ADVISORY_OUTPUT_TARGET_RE.test(target)) {\n\t\treturn true;\n\t}\n\tconst outputRequest = ADVISORY_OUTPUT_REQUEST_RE.exec(target);\n\tif (outputRequest && ADVISORY_OUTPUT_TARGET_RE.test(outputRequest[1] ?? \"\")) return true;\n\treturn LEADING_ADVISORY_REQUEST_RE.test(target);\n}\n\nfunction classifyConjoinedChangeRequest(target: string, options: { advisoryTopic?: boolean } = {}): ChangeRequestKind {\n\tconst maskedTarget = maskQuotedText(target);\n\tconst matches: Array<{ start: number; end: number; action: string }> = [];\n\tscanAfterBoundary(maskedTarget, FOLLOW_UP_CHANGE_TAIL_RE, (start, end, tailMatch) => {\n\t\tmatches.push({ start, end, action: tailMatch[1] ?? \"\" });\n\t\treturn false;\n\t});\n\tlet requestKind: ChangeRequestKind = \"none\";\n\n\tfor (const match of matches) {\n\t\tconst action = match.action.toLowerCase();\n\t\tif (!action) return \"substantive\";\n\n\t\t// Masking a suffix equals the suffix of the masked text: no quote span can cross the action word.\n\t\tconst editStart = match.end + target.slice(match.end).search(/\\S|$/);\n\t\tconst editTarget = target.slice(editStart);\n\t\tconst nextBoundary = FOLLOW_UP_CHANGE_BOUNDARY_RE.exec(maskedTarget.slice(editStart));\n\t\tconst clauseTarget = editTarget.slice(0, nextBoundary?.index ?? editTarget.length).trim();\n\t\tconst matchedText = maskedTarget.slice(match.start, match.end);\n\t\tif (\n\t\t\toptions.advisoryTopic &&\n\t\t\tADVISORY_TOPIC_COMPOUND_ACTION_RE.test(action) &&\n\t\t\tADVISORY_TOPIC_COMPOUND_HEAD_RE.test(clauseTarget) &&\n\t\t\t!EXPLICIT_FOLLOW_UP_REQUEST_RE.test(matchedText)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (ADVISORY_OUTPUT_ACTIONS.has(action) && ADVISORY_OUTPUT_TARGET_RE.test(clauseTarget)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!POTENTIALLY_BOUNDED_ACTIONS.has(action)) return \"substantive\";\n\t\tif (!isBoundedEditTarget(clauseTarget, action)) return \"substantive\";\n\t\tif (hasCoordinatedBoundedEditTarget(editTarget)) return \"substantive\";\n\t\tif (requestKind === \"bounded\") return \"substantive\";\n\t\trequestKind = \"bounded\";\n\t}\n\n\treturn requestKind;\n}\n\nfunction classifyNonImplementationDesire(target: string): ChangeRequestKind | null {\n\tif (!NON_IMPLEMENTATION_DESIRE_RE.test(target)) return null;\n\n\tconst advisoryTopic = NON_IMPLEMENTATION_TOPIC_RE.test(target);\n\tconst conjoinedRequest = classifyConjoinedChangeRequest(target, { advisoryTopic });\n\tif (conjoinedRequest !== \"none\") return conjoinedRequest;\n\tif (advisoryTopic) return \"none\";\n\n\tconst continuation = desiredStateContinuation(target);\n\treturn continuation && !isAdvisoryContinuation(continuation) ? \"substantive\" : \"none\";\n}\n\nfunction hasNonImplementationDesire(prompt: string): boolean {\n\tconst request = matchDesiredStateRequest(prompt);\n\tif (!request?.target) return false;\n\tconst requestKind = classifyNonImplementationDesire(request.target);\n\treturn requestKind !== null && requestKind !== \"substantive\";\n}\n\nfunction classifyChangeRequest(prompt: string): ChangeRequestKind {\n\tconst match = SUBSTANTIVE_CHANGE_REQUEST_RE.exec(prompt);\n\tif (match) {\n\t\tconst action = match[1]?.toLowerCase();\n\t\tif (!action || !POTENTIALLY_BOUNDED_ACTIONS.has(action)) return \"substantive\";\n\n\t\tconst target = prompt.slice(match[0].length).trimStart();\n\t\tconst conjoinedRequest = classifyConjoinedChangeRequest(prompt);\n\t\tif (!isBoundedEditTarget(firstChangeClauseTarget(target), action)) {\n\t\t\treturn action === \"rename\" && conjoinedRequest === \"none\" && !hasCoordinatedBoundedEditTarget(target)\n\t\t\t\t? \"none\"\n\t\t\t\t: \"substantive\";\n\t\t}\n\t\tif (hasCoordinatedBoundedEditTarget(target)) return \"substantive\";\n\t\treturn conjoinedRequest === \"none\" ? \"bounded\" : \"substantive\";\n\t}\n\n\tif (LEADING_ADVISORY_REQUEST_RE.test(prompt)) {\n\t\tconst conjoinedRequest = classifyConjoinedChangeRequest(prompt);\n\t\tif (conjoinedRequest !== \"none\") return conjoinedRequest;\n\t}\n\n\tconst desiredStateRequest = matchDesiredStateRequest(prompt);\n\tif (!desiredStateRequest) return \"none\";\n\tconst { target } = desiredStateRequest;\n\tif (target) {\n\t\tconst nonImplementationRequest = classifyNonImplementationDesire(target);\n\t\tif (nonImplementationRequest !== null) return nonImplementationRequest;\n\t}\n\treturn target && isBoundedEditTarget(target) ? \"bounded\" : \"substantive\";\n}\n\nfunction resolvePromptExecutionDepth(\n\ttrimmed: string,\n\tsignalText: string,\n\timperativeTotal: number,\n\tchangeRequestKind: ChangeRequestKind,\n): Pick<UnifiedPromptClassification, \"depth\" | \"depthReason\"> {\n\tif (!trimmed) return { depth: \"quick\", depthReason: \"empty-prompt\" };\n\tif (EXPLICIT_THOROUGH_BUILD_RE.test(signalText)) {\n\t\treturn { depth: \"thorough\", depthReason: \"explicit-thorough-request\" };\n\t}\n\tif (HIGH_RISK_BUILD_RE.test(signalText) && (COMPLEX_BUILD_RE.test(signalText) || imperativeTotal >= 2)) {\n\t\treturn { depth: \"thorough\", depthReason: \"high-risk-complexity\" };\n\t}\n\tif (signalText.length > 600 && imperativeTotal >= 3) {\n\t\treturn { depth: \"thorough\", depthReason: \"long-multi-imperative\" };\n\t}\n\tif (hasNonImplementationDesire(trimmed)) return { depth: \"quick\", depthReason: \"non-implementation-desire\" };\n\tif (changeRequestKind === \"bounded\") return { depth: \"quick\", depthReason: \"bounded-edit\" };\n\tconst starterRequest = SUBSTANTIVE_CHANGE_REQUEST_RE.exec(trimmed);\n\tif (\n\t\tstarterRequest &&\n\t\tHELLO_WORLD_STARTER_ACTION_RE.test(starterRequest[1] ?? \"\") &&\n\t\tHELLO_WORLD_STARTER_TARGET_RE.test(trimmed.slice(starterRequest[0].length).trim())\n\t) {\n\t\treturn { depth: \"quick\", depthReason: \"hello-world-starter\" };\n\t}\n\tif (COMPLEX_BUILD_RE.test(signalText)) return { depth: \"balanced\", depthReason: \"complexity-signal\" };\n\tif (changeRequestKind === \"substantive\") return { depth: \"balanced\", depthReason: \"substantive-change\" };\n\tif (hasNonLatinComplexitySignal(signalText)) return { depth: \"balanced\", depthReason: \"non-latin-complexity\" };\n\tif (signalText.length > 180 && imperativeTotal >= 2) return { depth: \"balanced\", depthReason: \"long-multi-change\" };\n\tif (hasMultiChangePrompt(signalText)) return { depth: \"balanced\", depthReason: \"multi-change\" };\n\treturn { depth: \"quick\", depthReason: \"default-quick\" };\n}\n\n// Independent of the resolved depth: a prompt can carry a risk signal (e.g.\n// a high-risk domain term) even on a turn where the overall heuristic above\n// settles on 'balanced' because no other arm fired. Consumers that gate on\n// risk (e.g. the review pass) rely on that independence rather than\n// re-deriving reasons from `depth`.\nfunction computeRiskReasons(trimmed: string, imperativeTotal: number): RiskReason[] {\n\tconst reasons: RiskReason[] = [];\n\tif (EXPLICIT_THOROUGH_BUILD_RE.test(trimmed)) reasons.push(\"explicit-thorough-request\");\n\tif (HIGH_RISK_BUILD_RE.test(trimmed)) reasons.push(\"high-risk-domain-term\");\n\tif (trimmed.length > 600 && imperativeTotal >= 3) reasons.push(\"long-multi-imperative\");\n\treturn reasons;\n}\n\nexport function classifyPromptLanguageBucket(prompt: string): \"latin\" | \"non-latin\" {\n\treturn NON_LATIN_RE.test(prompt) ? \"non-latin\" : \"latin\";\n}\n\nexport function classifyPromptSignals(input: { prompt: string; mode?: string | null }): UnifiedPromptClassification {\n\tconst trimmed = input.prompt.trim();\n\tconst signalText = maskQuotedText(trimmed);\n\tconst imperativeTotal = imperativeCount(signalText);\n\tconst changeRequestKind = classifyChangeRequest(trimmed);\n\tconst laneResult = classifyLane({\n\t\tprompt: changeRequestKind === \"bounded\" ? signalText : trimmed,\n\t\tmode: input.mode,\n\t});\n\treturn {\n\t\tlane: laneResult.lane,\n\t\tlaneDecisionSource: laneResult.decisionSource,\n\t\tlaneMatchedSignals: laneResult.matchedSignals,\n\t\t...resolvePromptExecutionDepth(trimmed, signalText, imperativeTotal, changeRequestKind),\n\t\triskReasons: computeRiskReasons(signalText, imperativeTotal),\n\t\tpolicyId: UNIFIED_CLASSIFIER_POLICY_ID,\n\t};\n}\n\nexport interface FlowSizeThresholds {\n\tmediumAt: number;\n\tlargeAt: number;\n}\n\n/**\n * Maps a classifier depth to a Flow size: quick -> small, balanced -> medium, thorough -> large.\n * When `thresholds` and a finite numeric `score` are both given, the score decides instead:\n * score >= largeAt -> large, score >= mediumAt -> medium, else small.\n */\nexport function sizeFromDepth(depth: PromptExecutionDepth, thresholds?: FlowSizeThresholds, score?: number): FlowSize {\n\tif (thresholds !== undefined && typeof score === \"number\" && Number.isFinite(score)) {\n\t\tif (score >= thresholds.largeAt) return \"large\";\n\t\treturn score >= thresholds.mediumAt ? \"medium\" : \"small\";\n\t}\n\tif (depth === \"thorough\") return \"large\";\n\treturn depth === \"balanced\" ? \"medium\" : \"small\";\n}\n"]}
|
package/dist/rpc.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["../src/rpc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAiC,KAAK,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAMtG,eAAO,MAAM,oBAAoB,QAAmB,CAAC;AACrD,eAAO,MAAM,iCAAiC,QAAmB,CAAC;AAClE,eAAO,MAAM,iCAAiC,QAAmB,CAAC;AAClE,eAAO,MAAM,uBAAuB,EAAG,kBAA2B,CAAC;AAEnE,QAAA,MAAM,kBAAkB,YAAI,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,CAAU,CAAC;AAChH,KAAK,eAAe,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["../src/rpc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAiC,KAAK,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAMtG,eAAO,MAAM,oBAAoB,QAAmB,CAAC;AACrD,eAAO,MAAM,iCAAiC,QAAmB,CAAC;AAClE,eAAO,MAAM,iCAAiC,QAAmB,CAAC;AAClE,eAAO,MAAM,uBAAuB,EAAG,kBAA2B,CAAC;AAEnE,QAAA,MAAM,kBAAkB,YAAI,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,CAAU,CAAC;AAChH,KAAK,eAAe,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAmD3D,MAAM,MAAM,cAAc,G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AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAc,EAAE,SAAiB;IACjE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,SAAS,CAAC;AACnF,CAAC;AAED,SAAS,eAAe,CAAC,KAAc,EAAE,SAAiB;IACzD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,IAAI,SAAS,CAAC;AAC/D,CAAC;AAED,SAAS,WAAW,CAAC,KAA8B,EAAE,OAA0B;IAC9E,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAChC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,IAAI,KAAK,IAAI,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;AACjH,CAAC;AAED,SAAS,aAAa,CAAC,GAAW;IACjC,OAAO,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,OAAO,IAAI,GAAG,KAAK,MAAM,CAAC;AAC1D,CAAC","sourcesContent":["import type { FlowControlCommandV1 } from \"./flow-control.ts\";\nimport { parseSubagentProgressSnapshot, type SubagentProgressSnapshot } from \"./subagent-progress.ts\";\n\nconst MAX_IDENTIFIER_LENGTH = 256;\nconst MAX_MESSAGE_LENGTH = 100_000;\nconst MAX_ERROR_LENGTH = 10_000;\nconst MAX_SESSION_PATH_LENGTH = 4_096;\nexport const MAX_RPC_FRAME_LENGTH = 16 * 1024 * 1024;\nexport const MAX_GET_STATE_RESPONSE_UTF8_BYTES = 16 * 1024 * 1024;\nexport const MAX_GET_STATE_RESPONSE_CODE_UNITS = 16 * 1024 * 1024;\nexport const SUBAGENT_PROGRESS_FIELD = \"subagentProgress\" as const;\n\nconst FLOW_COMMAND_TYPES = [\"flow_status\", \"flow_pause\", \"flow_resume\", \"flow_cancel\", \"flow_message\"] as const;\ntype FlowCommandType = (typeof FLOW_COMMAND_TYPES)[number];\nconst FLOW_ID_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,127}$/;\nconst FLOW_MESSAGE_MAX_LENGTH = 16_000;\nconst FLOW_RECEIPT_STATES = [\"accepted\", \"applied\", \"rejected\"];\nconst FLOW_CANCEL_REASONS = [\"user\", \"budget\", \"shutdown\", \"kill_switch\"];\nconst FLOW_DISPOSITIONS = [\"live\", \"queued\", \"rejected\"];\n// Mirrors FLOW_FAILURE_CLASSES + \"size_underestimated\" and FLOW_ROLES in ./flow-common (rpc.ts must stay import-free);\n// test/rpc.test.ts keeps the lists in sync.\nconst FLOW_REASON_CLASSES = [\n\t\"provider_error\",\n\t\"rate_limit\",\n\t\"timeout\",\n\t\"check_failed\",\n\t\"review_rejected\",\n\t\"qa_failed\",\n\t\"budget_stop\",\n\t\"cancelled\",\n\t\"crash\",\n\t\"unsafe_scope\",\n\t\"stalled\",\n\t\"config_invalid\",\n\t\"internal\",\n\t\"size_underestimated\",\n];\nconst FLOW_ROLE_NAMES = [\n\t\"scout\",\n\t\"worker\",\n\t\"implementer\",\n\t\"lead\",\n\t\"lead_large\",\n\t\"architect\",\n\t\"reviewer\",\n\t\"security_reviewer\",\n\t\"qa\",\n\t\"triage\",\n];\nconst INVALID_FRAME_MESSAGE = \"Invalid HUMAIN Code CLI RPC frame\";\nconst INVALID_COMMAND_MESSAGE = \"Invalid HUMAIN Code CLI RPC command\";\nconst MAX_SNAPSHOT_DEPTH = 16;\nconst MAX_SNAPSHOT_NODES = 10_000;\n// The snapshot string cap must never be below any field limit; per-field limits are enforced after the snapshot.\nconst MAX_SNAPSHOT_STRING = Math.max(\n\tMAX_IDENTIFIER_LENGTH,\n\tMAX_MESSAGE_LENGTH,\n\tMAX_ERROR_LENGTH,\n\tMAX_SESSION_PATH_LENGTH,\n\tFLOW_MESSAGE_MAX_LENGTH,\n);\n\nexport type RpcWireCommand =\n\t| { id: string; type: \"prompt\"; message: string }\n\t| { id: string; type: \"abort\" }\n\t| { id: string; type: \"get_state\" }\n\t| { type: \"set_model\"; provider: string; modelId: string }\n\t| { id: string; type: \"switch_session\"; sessionPath: string }\n\t| FlowControlCommandV1;\n\nexport type RpcReadyFrame = {\n\ttype: \"ready\";\n\tprotocolVersion: 1;\n\tsessionId: string;\n\tpid: number;\n};\n\nexport type RpcResponseFrame = {\n\ttype: \"response\";\n\tid?: string;\n\tcommand: string;\n\tsuccess: boolean;\n\terror?: string;\n\tdata?: unknown;\n};\n\n/** Flow receipt: a `response` frame without `success`. Fully validated by `parseRpcWireFrame` (no TypeBox needed). */\nexport type RpcFlowReceiptFrame = {\n\ttype: \"response\";\n\tid: string;\n\tcommand: FlowCommandType;\n\tstate: \"accepted\" | \"applied\" | \"rejected\";\n\t[key: string]: unknown;\n};\n/**\n * Pushed flow frames: `parseRpcWireFrame` validates the ENVELOPE only (exactly `{type, event}` / `{type, status}`\n * with a plain-object payload) because rpc.ts must stay TypeBox-free. Consumers MUST pass `event` to\n * `parseFlowEventV1` (./flow-events) and `status` to `parseFlowStatusV1` (./flow-control) before using it.\n */\nexport type RpcFlowEventFrame = { type: \"flow_event\"; event: Record<string, unknown> };\nexport type RpcFlowStatusFrame = { type: \"flow_status\"; status: Record<string, unknown> };\n\nexport type RpcNativeEventFrame = { type: string; [key: string]: unknown };\nexport type RpcSubagentProgressMetadata = { subagentProgress?: SubagentProgressSnapshot };\nexport type RpcToolExecutionUpdateProgressFrame = RpcNativeEventFrame & {\n\ttype: \"tool_execution_update\";\n} & RpcSubagentProgressMetadata;\nexport type RpcToolExecutionEndProgressFrame = RpcNativeEventFrame & {\n\ttype: \"tool_execution_end\";\n} & RpcSubagentProgressMetadata;\nexport type RpcGetStateProgressData = Record<string, unknown> & RpcSubagentProgressMetadata;\nexport type RpcWireFrame =\n\t| RpcReadyFrame\n\t| RpcResponseFrame\n\t| RpcFlowReceiptFrame\n\t| RpcFlowEventFrame\n\t| RpcFlowStatusFrame\n\t| RpcNativeEventFrame;\n\nexport function encodeRpcWireCommand(command: RpcWireCommand): string {\n\tconst type = readOwnDiscriminant(command, \"type\", INVALID_COMMAND_MESSAGE);\n\tif (typeof type !== \"string\" || !type.startsWith(\"flow_\")) {\n\t\t// Legacy commands keep the contracts 0.3.3 validate-then-stringify behavior.\n\t\tif (!isRpcWireCommand(command)) throw new Error(INVALID_COMMAND_MESSAGE);\n\t\tconst encoded = JSON.stringify(command);\n\t\t// A proxy can answer differently per read; the serialized type must be the classified one.\n\t\tif ((JSON.parse(encoded) as { type?: unknown }).type !== type) throw new Error(INVALID_COMMAND_MESSAGE);\n\t\treturn `${encoded}\\n`;\n\t}\n\t// Flow commands: validate and serialize one plain-data snapshot so getters/proxies cannot change between check and write.\n\tlet snapshot: unknown;\n\ttry {\n\t\tsnapshot = snapshotPlainData(command, 0, { nodes: 0 });\n\t} catch {\n\t\tthrow new Error(INVALID_COMMAND_MESSAGE);\n\t}\n\tif (!isRpcWireCommand(snapshot)) throw new Error(INVALID_COMMAND_MESSAGE);\n\treturn `${JSON.stringify(snapshot)}\\n`;\n}\n\n/**\n * Reads a discriminant once as an OWN DATA property. Inherited or accessor discriminants throw: this is an\n * intentional, security-motivated exception to contracts 0.3.3 parity (a changing/inherited discriminant could\n * select the unvalidated path). Absent returns undefined. Non-records throw.\n */\nfunction readOwnDiscriminant(target: unknown, key: string, message: string): unknown {\n\tif (!isRecord(target)) throw new Error(message);\n\tlet descriptor: PropertyDescriptor | undefined;\n\tlet inherited = false;\n\ttry {\n\t\tdescriptor = Object.getOwnPropertyDescriptor(target, key);\n\t\tinherited = descriptor === undefined && key in target;\n\t} catch {\n\t\tthrow new Error(message);\n\t}\n\tif (inherited || (descriptor !== undefined && !(\"value\" in descriptor))) throw new Error(message);\n\treturn descriptor?.value;\n}\n\n/** Same rules as `snapshotFlowData` in ./flow-common (duplicated: this entry must not import anything). */\nfunction snapshotPlainData(value: unknown, depth: number, budget: { nodes: number }): unknown {\n\tbudget.nodes += 1;\n\tif (depth > MAX_SNAPSHOT_DEPTH || budget.nodes > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\tif (value === null || typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tif (value.length > MAX_SNAPSHOT_STRING || !value.isWellFormed()) throw new Error(\"string\");\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new Error(\"number\");\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") throw new Error(\"type\");\n\tif (Array.isArray(value)) {\n\t\tconst length = value.length;\n\t\tif (length > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (\n\t\t\t\ttypeof key !== \"string\" ||\n\t\t\t\t(key !== \"length\" &&\n\t\t\t\t\t!(\n\t\t\t\t\t\tNumber.isInteger(Number(key)) &&\n\t\t\t\t\t\tNumber(key) >= 0 &&\n\t\t\t\t\t\tNumber(key) < length &&\n\t\t\t\t\t\tString(Number(key)) === key\n\t\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"array\");\n\t\t\t}\n\t\t}\n\t\tconst out: unknown[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\tif (descriptor === undefined || !(\"value\" in descriptor)) throw new Error(\"array\");\n\t\t\tout.push(snapshotPlainData(descriptor.value, depth + 1, budget));\n\t\t}\n\t\treturn out;\n\t}\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== null && Object.getPrototypeOf(proto) !== null) throw new Error(\"prototype\");\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tif (typeof key !== \"string\" || !key.isWellFormed()) throw new Error(\"key\");\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor === undefined || !(\"value\" in descriptor) || descriptor.enumerable !== true)\n\t\t\tthrow new Error(\"property\");\n\t\tif (descriptor.value === undefined) continue;\n\t\tObject.defineProperty(out, key, {\n\t\t\tvalue: snapshotPlainData(descriptor.value, depth + 1, budget),\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn out;\n}\n\n/**\n * One-level snapshot of a frame: own enumerable string-keyed DATA properties are copied (each read once); an\n * accessor, a throwing trap or a non-record is the constant invalid-frame error. Discriminants are read only from\n * the copy. Nested values are untouched here (native events pass through; flow frames are deep-snapshotted later).\n */\nfunction copyFrameData(frame: unknown): Record<string, unknown> {\n\ttry {\n\t\tif (!isRecord(frame)) throw new Error(\"record\");\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const key of Reflect.ownKeys(frame)) {\n\t\t\tif (typeof key !== \"string\") continue;\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(frame, key);\n\t\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\t\tif (!(\"value\" in descriptor)) throw new Error(\"accessor\");\n\t\t\tObject.defineProperty(out, key, {\n\t\t\t\tvalue: descriptor.value,\n\t\t\t\tenumerable: true,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t} catch {\n\t\tthrow new Error(INVALID_FRAME_MESSAGE);\n\t}\n}\n\n/** Deep plain snapshot of an (already copied) flow frame. */\nfunction snapshotFlowFrame(frame: Record<string, unknown>): Record<string, unknown> {\n\ttry {\n\t\treturn snapshotPlainData(frame, 0, { nodes: 0 }) as Record<string, unknown>;\n\t} catch {\n\t\tthrow new Error(INVALID_FRAME_MESSAGE);\n\t}\n}\n\nfunction validateFlowFrame(\n\tframe: Record<string, unknown>,\n): RpcFlowReceiptFrame | RpcFlowEventFrame | RpcFlowStatusFrame {\n\tif (frame.type === \"flow_event\" || frame.type === \"flow_status\") {\n\t\tconst payload = frame.type === \"flow_event\" ? \"event\" : \"status\";\n\t\tif (!hasExactKeys(frame, [\"type\", payload], []) || !isRecord(frame[payload]))\n\t\t\tthrow new Error(INVALID_FRAME_MESSAGE);\n\t\treturn frame as RpcFlowEventFrame | RpcFlowStatusFrame;\n\t}\n\tif (!isFlowReceiptFrame(frame)) throw new Error(INVALID_FRAME_MESSAGE);\n\treturn frame as RpcFlowReceiptFrame;\n}\n\nexport function parseRpcWireFrame(input: unknown): RpcWireFrame {\n\tif (typeof input === \"string\" && input.length > MAX_RPC_FRAME_LENGTH) {\n\t\tthrow new Error(`HUMAIN Code CLI RPC frame exceeds the ${MAX_RPC_FRAME_LENGTH}-character limit`);\n\t}\n\tlet frame: unknown = input;\n\tif (typeof input === \"string\") {\n\t\ttry {\n\t\t\tframe = JSON.parse(input);\n\t\t} catch {\n\t\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t\t}\n\t}\n\t// ponytail: proxy frames are not defended (limit: in-process code building a proxy already controls the process).\n\tconst type = readOwnDiscriminant(frame, \"type\", INVALID_FRAME_MESSAGE);\n\tconst record = frame as Record<string, unknown>;\n\tconst command = type === \"response\" ? readOwnDiscriminant(record, \"command\", INVALID_FRAME_MESSAGE) : undefined;\n\tconst success = type === \"response\" ? readOwnDiscriminant(record, \"success\", INVALID_FRAME_MESSAGE) : undefined;\n\t// HC emits `{success:false,error}` for invalid flow_* commands and Flow handler exceptions; keep the legacy path.\n\tconst isLegacyErrorResponse = () =>\n\t\tsuccess === false && typeof Object.getOwnPropertyDescriptor(record, \"error\")?.value === \"string\";\n\tif (\n\t\ttype === \"flow_event\" ||\n\t\ttype === \"flow_status\" ||\n\t\t(type === \"response\" && typeof command === \"string\" && command.startsWith(\"flow_\") && !isLegacyErrorResponse())\n\t) {\n\t\tconst flowFrame = snapshotFlowFrame(copyFrameData(record));\n\t\treturn validateFlowFrame(flowFrame);\n\t}\n\tif (typeof type !== \"string\" || type.length === 0) {\n\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t}\n\tif (type === \"ready\") {\n\t\tif (\n\t\t\t!hasOnlyKeys(record, [\"type\", \"protocolVersion\", \"sessionId\", \"pid\"]) ||\n\t\t\trecord.protocolVersion !== 1 ||\n\t\t\t!isNonemptyBoundedString(record.sessionId, MAX_IDENTIFIER_LENGTH) ||\n\t\t\t!Number.isSafeInteger(record.pid) ||\n\t\t\t(record.pid as number) <= 0\n\t\t) {\n\t\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t\t}\n\t\treturn record as RpcReadyFrame;\n\t}\n\tif (type === \"response\") {\n\t\tif (\n\t\t\t!hasOnlyKeys(record, [\"type\", \"id\", \"command\", \"success\", \"error\", \"data\"]) ||\n\t\t\t(record.id !== undefined && !isNonemptyBoundedString(record.id, MAX_IDENTIFIER_LENGTH)) ||\n\t\t\t!isNonemptyBoundedString(command, MAX_IDENTIFIER_LENGTH) ||\n\t\t\ttypeof success !== \"boolean\" ||\n\t\t\t(record.error !== undefined && !isBoundedString(record.error, MAX_ERROR_LENGTH))\n\t\t) {\n\t\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t\t}\n\t\treturn record as RpcResponseFrame;\n\t}\n\treturn frame as RpcNativeEventFrame;\n}\n\n/**\n * Reads optional subagent progress metadata. Absent field means unsupported/unavailable\n * (returns undefined); a present field is strictly parsed and throws when invalid.\n * Update/end piggyback envelopes must carry exactly one run (0 or 2+ throws); get_state accepts 0..64 runs.\n * No other frame fields are inspected or validated.\n */\nexport function readRpcSubagentProgress(frame: RpcWireFrame): SubagentProgressSnapshot | undefined {\n\ttry {\n\t\treturn extractRpcSubagentProgress(frame);\n\t} catch {\n\t\tthrow new Error(INVALID_PROGRESS_MESSAGE);\n\t}\n}\n\nconst INVALID_PROGRESS_MESSAGE = \"Invalid subagent progress snapshot\";\n\n/** Own data property lookup: never invokes getters; `inherited` is true when only a non-own property exists. */\nfunction readOwnData(target: object, key: string): { found: boolean; value?: unknown; inherited: boolean } {\n\tconst descriptor = Object.getOwnPropertyDescriptor(target, key);\n\tif (descriptor === undefined) return { found: false, inherited: key in target };\n\tif (!(\"value\" in descriptor)) throw new Error(INVALID_PROGRESS_MESSAGE);\n\treturn { found: true, value: descriptor.value, inherited: false };\n}\n\nfunction extractRpcSubagentProgress(frame: RpcWireFrame): SubagentProgressSnapshot | undefined {\n\tif (!isRecord(frame)) return undefined;\n\tconst type = readOwnData(frame, \"type\").value;\n\tlet carrier: unknown;\n\tlet singleRun = false;\n\tif (type === \"tool_execution_update\" || type === \"tool_execution_end\") {\n\t\tcarrier = frame;\n\t\tsingleRun = true;\n\t} else if (type === \"response\") {\n\t\tif (readOwnData(frame, \"command\").value !== \"get_state\" || readOwnData(frame, \"success\").value !== true) {\n\t\t\treturn undefined;\n\t\t}\n\t\tcarrier = readOwnData(frame, \"data\").value;\n\t} else {\n\t\treturn undefined;\n\t}\n\tif (!isRecord(carrier)) return undefined;\n\tconst field = readOwnData(carrier, SUBAGENT_PROGRESS_FIELD);\n\tif (field.inherited) throw new Error(INVALID_PROGRESS_MESSAGE);\n\tif (!field.found) return undefined;\n\tconst snapshot = parseSubagentProgressSnapshot(field.value);\n\tif (singleRun && snapshot.runs.length !== 1) throw new Error(INVALID_PROGRESS_MESSAGE);\n\treturn snapshot;\n}\n\nfunction isRpcWireCommand(value: unknown): value is RpcWireCommand {\n\tif (!isRecord(value)) return false;\n\tswitch (value.type) {\n\t\tcase \"prompt\":\n\t\t\treturn (\n\t\t\t\thasOnlyKeys(value, [\"id\", \"type\", \"message\"]) &&\n\t\t\t\tisNonemptyBoundedString(value.id, MAX_IDENTIFIER_LENGTH) &&\n\t\t\t\tisNonemptyBoundedString(value.message, MAX_MESSAGE_LENGTH)\n\t\t\t);\n\t\tcase \"abort\":\n\t\tcase \"get_state\":\n\t\t\treturn hasOnlyKeys(value, [\"id\", \"type\"]) && isNonemptyBoundedString(value.id, MAX_IDENTIFIER_LENGTH);\n\t\tcase \"set_model\":\n\t\t\treturn (\n\t\t\t\thasOnlyKeys(value, [\"type\", \"provider\", \"modelId\"]) &&\n\t\t\t\tisNonemptyBoundedString(value.provider, MAX_IDENTIFIER_LENGTH) &&\n\t\t\t\tisNonemptyBoundedString(value.modelId, MAX_IDENTIFIER_LENGTH)\n\t\t\t);\n\t\tcase \"switch_session\":\n\t\t\treturn (\n\t\t\t\thasOnlyKeys(value, [\"id\", \"type\", \"sessionPath\"]) &&\n\t\t\t\tisNonemptyBoundedString(value.id, MAX_IDENTIFIER_LENGTH) &&\n\t\t\t\tisNonemptyBoundedString(value.sessionPath, MAX_SESSION_PATH_LENGTH)\n\t\t\t);\n\t\tcase \"flow_status\":\n\t\t\treturn (\n\t\t\t\thasExactKeys(value, [\"id\", \"type\"], [\"runId\"]) &&\n\t\t\t\tisFlowId(value.id) &&\n\t\t\t\t(!(\"runId\" in value) || isFlowId(value.runId))\n\t\t\t);\n\t\tcase \"flow_pause\":\n\t\tcase \"flow_resume\":\n\t\t\treturn hasExactKeys(value, [\"id\", \"type\", \"runId\"], []) && isFlowId(value.id) && isFlowId(value.runId);\n\t\tcase \"flow_cancel\":\n\t\t\treturn (\n\t\t\t\thasExactKeys(value, [\"id\", \"type\", \"runId\", \"reason\"], []) &&\n\t\t\t\tisFlowId(value.id) &&\n\t\t\t\tisFlowId(value.runId) &&\n\t\t\t\tFLOW_CANCEL_REASONS.includes(value.reason as string)\n\t\t\t);\n\t\tcase \"flow_message\":\n\t\t\treturn (\n\t\t\t\thasExactKeys(value, [\"id\", \"type\", \"runId\", \"messageId\", \"text\"], [\"target\"]) &&\n\t\t\t\tisFlowId(value.id) &&\n\t\t\t\tisFlowId(value.runId) &&\n\t\t\t\tisFlowId(value.messageId) &&\n\t\t\t\tisNonemptyBoundedString(value.text, FLOW_MESSAGE_MAX_LENGTH) &&\n\t\t\t\t(value.target === undefined ||\n\t\t\t\t\tvalue.target === \"lead\" ||\n\t\t\t\t\t(isRecord(value.target) && hasExactKeys(value.target, [\"taskId\"], []) && isFlowId(value.target.taskId)))\n\t\t\t);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction isFlowCommandType(value: unknown): value is FlowCommandType {\n\treturn FLOW_COMMAND_TYPES.includes(value as FlowCommandType);\n}\n\nfunction isFlowId(value: unknown): value is string {\n\treturn typeof value === \"string\" && FLOW_ID_PATTERN.test(value);\n}\n\nfunction hasExactKeys(\n\tvalue: Record<string, unknown>,\n\trequired: readonly string[],\n\toptional: readonly string[],\n): boolean {\n\treturn (\n\t\tObject.keys(value).every((key) => required.includes(key) || optional.includes(key)) &&\n\t\trequired.every((key) => key in value)\n\t);\n}\n\n/** Full receipt validation (state, reason, terminationConfirmed only for cancel, disposition/deliveredTo only for messages). */\nfunction isFlowReceiptFrame(frame: Record<string, unknown>): boolean {\n\tconst message = frame.command === \"flow_message\";\n\tconst cancel = frame.command === \"flow_cancel\";\n\tif (\n\t\t!hasExactKeys(\n\t\t\tframe,\n\t\t\t[\"type\", \"id\", \"command\", \"state\", ...(message ? [\"messageId\", \"disposition\"] : [])],\n\t\t\t[\"reason\", ...(message ? [\"deliveredTo\"] : cancel ? [\"terminationConfirmed\"] : [])],\n\t\t) ||\n\t\tframe.type !== \"response\" ||\n\t\t!isFlowCommandType(frame.command) ||\n\t\t!isFlowId(frame.id) ||\n\t\t!FLOW_RECEIPT_STATES.includes(frame.state as string) ||\n\t\t(frame.reason !== undefined && !FLOW_REASON_CLASSES.includes(frame.reason as string))\n\t) {\n\t\treturn false;\n\t}\n\tif (cancel) return frame.terminationConfirmed === undefined || typeof frame.terminationConfirmed === \"boolean\";\n\tif (!message) return true;\n\tconst delivered = frame.deliveredTo;\n\treturn (\n\t\tisFlowId(frame.messageId) &&\n\t\tFLOW_DISPOSITIONS.includes(frame.disposition as string) &&\n\t\t(delivered === undefined ||\n\t\t\t(isRecord(delivered) &&\n\t\t\t\thasExactKeys(delivered, [\"taskId\", \"role\"], []) &&\n\t\t\t\tisFlowId(delivered.taskId) &&\n\t\t\t\tFLOW_ROLE_NAMES.includes(delivered.role as string)))\n\t);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonemptyBoundedString(value: unknown, maxLength: number): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n}\n\nfunction isBoundedString(value: unknown, maxLength: number): value is string {\n\treturn typeof value === \"string\" && value.length <= maxLength;\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, allowed: readonly string[]): boolean {\n\tconst keys = Object.keys(value);\n\treturn keys.every((key) => allowed.includes(key)) && allowed.every((key) => key in value || isOptionalKey(key));\n}\n\nfunction isOptionalKey(key: string): boolean {\n\treturn key === \"id\" || key === \"error\" || key === \"data\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../src/rpc.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAiC,MAAM,wBAAwB,CAAC;AAEtG,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,kBAAkB,GAAG,OAAO,CAAC;AACnC,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,uBAAuB,GAAG,KAAK,CAAC;AACtC,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACrD,MAAM,CAAC,MAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAClE,MAAM,CAAC,MAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAClE,MAAM,CAAC,MAAM,uBAAuB,GAAG,kBAA2B,CAAC;AAEnE,MAAM,kBAA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C,MAAM,IAAI,SAAS,CAAC;AAC/D,CAAC;AAED,SAAS,WAAW,CAAC,KAA8B,EAAE,OAA0B;IAC9E,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAChC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,IAAI,KAAK,IAAI,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;AACjH,CAAC;AAED,SAAS,aAAa,CAAC,GAAW;IACjC,OAAO,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,OAAO,IAAI,GAAG,KAAK,MAAM,CAAC;AAC1D,CAAC","sourcesContent":["import type { FlowControlCommandV1 } from \"./flow-control.ts\";\nimport { parseSubagentProgressSnapshot, type SubagentProgressSnapshot } from \"./subagent-progress.ts\";\n\nconst MAX_IDENTIFIER_LENGTH = 256;\nconst MAX_MESSAGE_LENGTH = 100_000;\nconst MAX_ERROR_LENGTH = 10_000;\nconst MAX_SESSION_PATH_LENGTH = 4_096;\nexport const MAX_RPC_FRAME_LENGTH = 16 * 1024 * 1024;\nexport const MAX_GET_STATE_RESPONSE_UTF8_BYTES = 16 * 1024 * 1024;\nexport const MAX_GET_STATE_RESPONSE_CODE_UNITS = 16 * 1024 * 1024;\nexport const SUBAGENT_PROGRESS_FIELD = \"subagentProgress\" as const;\n\nconst FLOW_COMMAND_TYPES = [\"flow_status\", \"flow_pause\", \"flow_resume\", \"flow_cancel\", \"flow_message\"] as const;\ntype FlowCommandType = (typeof FLOW_COMMAND_TYPES)[number];\nconst FLOW_ID_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,127}$/;\nconst FLOW_MESSAGE_MAX_LENGTH = 16_000;\nconst FLOW_RECEIPT_STATES = [\"accepted\", \"applied\", \"rejected\"];\nconst FLOW_CANCEL_REASONS = [\"user\", \"budget\", \"shutdown\", \"kill_switch\"];\nconst FLOW_DISPOSITIONS = [\"live\", \"queued\", \"rejected\"];\n// Mirrors FLOW_FAILURE_CLASSES + \"size_underestimated\" and FLOW_ROLES in ./flow-common (rpc.ts must stay import-free);\n// test/rpc.test.ts keeps the lists in sync.\nconst FLOW_REASON_CLASSES = [\n\t\"provider_error\",\n\t\"rate_limit\",\n\t\"timeout\",\n\t\"check_failed\",\n\t\"review_rejected\",\n\t\"qa_failed\",\n\t\"budget_stop\",\n\t\"cancelled\",\n\t\"crash\",\n\t\"unsafe_scope\",\n\t\"stalled\",\n\t\"config_invalid\",\n\t\"internal\",\n\t\"review_verdict_missing\",\n\t\"verification_unavailable\",\n\t\"size_underestimated\",\n];\nconst FLOW_ROLE_NAMES = [\n\t\"scout\",\n\t\"worker\",\n\t\"implementer\",\n\t\"lead\",\n\t\"lead_large\",\n\t\"architect\",\n\t\"reviewer\",\n\t\"security_reviewer\",\n\t\"qa\",\n\t\"triage\",\n];\nconst INVALID_FRAME_MESSAGE = \"Invalid HUMAIN Code CLI RPC frame\";\nconst INVALID_COMMAND_MESSAGE = \"Invalid HUMAIN Code CLI RPC command\";\nconst MAX_SNAPSHOT_DEPTH = 16;\nconst MAX_SNAPSHOT_NODES = 10_000;\n// The snapshot string cap must never be below any field limit; per-field limits are enforced after the snapshot.\nconst MAX_SNAPSHOT_STRING = Math.max(\n\tMAX_IDENTIFIER_LENGTH,\n\tMAX_MESSAGE_LENGTH,\n\tMAX_ERROR_LENGTH,\n\tMAX_SESSION_PATH_LENGTH,\n\tFLOW_MESSAGE_MAX_LENGTH,\n);\n\nexport type RpcWireCommand =\n\t| { id: string; type: \"prompt\"; message: string }\n\t| { id: string; type: \"abort\" }\n\t| { id: string; type: \"get_state\" }\n\t| { type: \"set_model\"; provider: string; modelId: string }\n\t| { id: string; type: \"switch_session\"; sessionPath: string }\n\t| FlowControlCommandV1;\n\nexport type RpcReadyFrame = {\n\ttype: \"ready\";\n\tprotocolVersion: 1;\n\tsessionId: string;\n\tpid: number;\n};\n\nexport type RpcResponseFrame = {\n\ttype: \"response\";\n\tid?: string;\n\tcommand: string;\n\tsuccess: boolean;\n\terror?: string;\n\tdata?: unknown;\n};\n\n/** Flow receipt: a `response` frame without `success`. Fully validated by `parseRpcWireFrame` (no TypeBox needed). */\nexport type RpcFlowReceiptFrame = {\n\ttype: \"response\";\n\tid: string;\n\tcommand: FlowCommandType;\n\tstate: \"accepted\" | \"applied\" | \"rejected\";\n\t[key: string]: unknown;\n};\n/**\n * Pushed flow frames: `parseRpcWireFrame` validates the ENVELOPE only (exactly `{type, event}` / `{type, status}`\n * with a plain-object payload) because rpc.ts must stay TypeBox-free. Consumers MUST pass `event` to\n * `parseFlowEventV1` (./flow-events) and `status` to `parseFlowStatusV1` (./flow-control) before using it.\n */\nexport type RpcFlowEventFrame = { type: \"flow_event\"; event: Record<string, unknown> };\nexport type RpcFlowStatusFrame = { type: \"flow_status\"; status: Record<string, unknown> };\n\nexport type RpcNativeEventFrame = { type: string; [key: string]: unknown };\nexport type RpcSubagentProgressMetadata = { subagentProgress?: SubagentProgressSnapshot };\nexport type RpcToolExecutionUpdateProgressFrame = RpcNativeEventFrame & {\n\ttype: \"tool_execution_update\";\n} & RpcSubagentProgressMetadata;\nexport type RpcToolExecutionEndProgressFrame = RpcNativeEventFrame & {\n\ttype: \"tool_execution_end\";\n} & RpcSubagentProgressMetadata;\nexport type RpcGetStateProgressData = Record<string, unknown> & RpcSubagentProgressMetadata;\nexport type RpcWireFrame =\n\t| RpcReadyFrame\n\t| RpcResponseFrame\n\t| RpcFlowReceiptFrame\n\t| RpcFlowEventFrame\n\t| RpcFlowStatusFrame\n\t| RpcNativeEventFrame;\n\nexport function encodeRpcWireCommand(command: RpcWireCommand): string {\n\tconst type = readOwnDiscriminant(command, \"type\", INVALID_COMMAND_MESSAGE);\n\tif (typeof type !== \"string\" || !type.startsWith(\"flow_\")) {\n\t\t// Legacy commands keep the contracts 0.3.3 validate-then-stringify behavior.\n\t\tif (!isRpcWireCommand(command)) throw new Error(INVALID_COMMAND_MESSAGE);\n\t\tconst encoded = JSON.stringify(command);\n\t\t// A proxy can answer differently per read; the serialized type must be the classified one.\n\t\tif ((JSON.parse(encoded) as { type?: unknown }).type !== type) throw new Error(INVALID_COMMAND_MESSAGE);\n\t\treturn `${encoded}\\n`;\n\t}\n\t// Flow commands: validate and serialize one plain-data snapshot so getters/proxies cannot change between check and write.\n\tlet snapshot: unknown;\n\ttry {\n\t\tsnapshot = snapshotPlainData(command, 0, { nodes: 0 });\n\t} catch {\n\t\tthrow new Error(INVALID_COMMAND_MESSAGE);\n\t}\n\tif (!isRpcWireCommand(snapshot)) throw new Error(INVALID_COMMAND_MESSAGE);\n\treturn `${JSON.stringify(snapshot)}\\n`;\n}\n\n/**\n * Reads a discriminant once as an OWN DATA property. Inherited or accessor discriminants throw: this is an\n * intentional, security-motivated exception to contracts 0.3.3 parity (a changing/inherited discriminant could\n * select the unvalidated path). Absent returns undefined. Non-records throw.\n */\nfunction readOwnDiscriminant(target: unknown, key: string, message: string): unknown {\n\tif (!isRecord(target)) throw new Error(message);\n\tlet descriptor: PropertyDescriptor | undefined;\n\tlet inherited = false;\n\ttry {\n\t\tdescriptor = Object.getOwnPropertyDescriptor(target, key);\n\t\tinherited = descriptor === undefined && key in target;\n\t} catch {\n\t\tthrow new Error(message);\n\t}\n\tif (inherited || (descriptor !== undefined && !(\"value\" in descriptor))) throw new Error(message);\n\treturn descriptor?.value;\n}\n\n/** Same rules as `snapshotFlowData` in ./flow-common (duplicated: this entry must not import anything). */\nfunction snapshotPlainData(value: unknown, depth: number, budget: { nodes: number }): unknown {\n\tbudget.nodes += 1;\n\tif (depth > MAX_SNAPSHOT_DEPTH || budget.nodes > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\tif (value === null || typeof value === \"boolean\") return value;\n\tif (typeof value === \"string\") {\n\t\tif (value.length > MAX_SNAPSHOT_STRING || !value.isWellFormed()) throw new Error(\"string\");\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new Error(\"number\");\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") throw new Error(\"type\");\n\tif (Array.isArray(value)) {\n\t\tconst length = value.length;\n\t\tif (length > MAX_SNAPSHOT_NODES) throw new Error(\"bounds\");\n\t\tfor (const key of Reflect.ownKeys(value)) {\n\t\t\tif (\n\t\t\t\ttypeof key !== \"string\" ||\n\t\t\t\t(key !== \"length\" &&\n\t\t\t\t\t!(\n\t\t\t\t\t\tNumber.isInteger(Number(key)) &&\n\t\t\t\t\t\tNumber(key) >= 0 &&\n\t\t\t\t\t\tNumber(key) < length &&\n\t\t\t\t\t\tString(Number(key)) === key\n\t\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"array\");\n\t\t\t}\n\t\t}\n\t\tconst out: unknown[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\tif (descriptor === undefined || !(\"value\" in descriptor)) throw new Error(\"array\");\n\t\t\tout.push(snapshotPlainData(descriptor.value, depth + 1, budget));\n\t\t}\n\t\treturn out;\n\t}\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== null && Object.getPrototypeOf(proto) !== null) throw new Error(\"prototype\");\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Reflect.ownKeys(value)) {\n\t\tif (typeof key !== \"string\" || !key.isWellFormed()) throw new Error(\"key\");\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor === undefined || !(\"value\" in descriptor) || descriptor.enumerable !== true)\n\t\t\tthrow new Error(\"property\");\n\t\tif (descriptor.value === undefined) continue;\n\t\tObject.defineProperty(out, key, {\n\t\t\tvalue: snapshotPlainData(descriptor.value, depth + 1, budget),\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn out;\n}\n\n/**\n * One-level snapshot of a frame: own enumerable string-keyed DATA properties are copied (each read once); an\n * accessor, a throwing trap or a non-record is the constant invalid-frame error. Discriminants are read only from\n * the copy. Nested values are untouched here (native events pass through; flow frames are deep-snapshotted later).\n */\nfunction copyFrameData(frame: unknown): Record<string, unknown> {\n\ttry {\n\t\tif (!isRecord(frame)) throw new Error(\"record\");\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const key of Reflect.ownKeys(frame)) {\n\t\t\tif (typeof key !== \"string\") continue;\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(frame, key);\n\t\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\t\tif (!(\"value\" in descriptor)) throw new Error(\"accessor\");\n\t\t\tObject.defineProperty(out, key, {\n\t\t\t\tvalue: descriptor.value,\n\t\t\t\tenumerable: true,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t} catch {\n\t\tthrow new Error(INVALID_FRAME_MESSAGE);\n\t}\n}\n\n/** Deep plain snapshot of an (already copied) flow frame. */\nfunction snapshotFlowFrame(frame: Record<string, unknown>): Record<string, unknown> {\n\ttry {\n\t\treturn snapshotPlainData(frame, 0, { nodes: 0 }) as Record<string, unknown>;\n\t} catch {\n\t\tthrow new Error(INVALID_FRAME_MESSAGE);\n\t}\n}\n\nfunction validateFlowFrame(\n\tframe: Record<string, unknown>,\n): RpcFlowReceiptFrame | RpcFlowEventFrame | RpcFlowStatusFrame {\n\tif (frame.type === \"flow_event\" || frame.type === \"flow_status\") {\n\t\tconst payload = frame.type === \"flow_event\" ? \"event\" : \"status\";\n\t\tif (!hasExactKeys(frame, [\"type\", payload], []) || !isRecord(frame[payload]))\n\t\t\tthrow new Error(INVALID_FRAME_MESSAGE);\n\t\treturn frame as RpcFlowEventFrame | RpcFlowStatusFrame;\n\t}\n\tif (!isFlowReceiptFrame(frame)) throw new Error(INVALID_FRAME_MESSAGE);\n\treturn frame as RpcFlowReceiptFrame;\n}\n\nexport function parseRpcWireFrame(input: unknown): RpcWireFrame {\n\tif (typeof input === \"string\" && input.length > MAX_RPC_FRAME_LENGTH) {\n\t\tthrow new Error(`HUMAIN Code CLI RPC frame exceeds the ${MAX_RPC_FRAME_LENGTH}-character limit`);\n\t}\n\tlet frame: unknown = input;\n\tif (typeof input === \"string\") {\n\t\ttry {\n\t\t\tframe = JSON.parse(input);\n\t\t} catch {\n\t\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t\t}\n\t}\n\t// ponytail: proxy frames are not defended (limit: in-process code building a proxy already controls the process).\n\tconst type = readOwnDiscriminant(frame, \"type\", INVALID_FRAME_MESSAGE);\n\tconst record = frame as Record<string, unknown>;\n\tconst command = type === \"response\" ? readOwnDiscriminant(record, \"command\", INVALID_FRAME_MESSAGE) : undefined;\n\tconst success = type === \"response\" ? readOwnDiscriminant(record, \"success\", INVALID_FRAME_MESSAGE) : undefined;\n\t// HC emits `{success:false,error}` for invalid flow_* commands and Flow handler exceptions; keep the legacy path.\n\tconst isLegacyErrorResponse = () =>\n\t\tsuccess === false && typeof Object.getOwnPropertyDescriptor(record, \"error\")?.value === \"string\";\n\tif (\n\t\ttype === \"flow_event\" ||\n\t\ttype === \"flow_status\" ||\n\t\t(type === \"response\" && typeof command === \"string\" && command.startsWith(\"flow_\") && !isLegacyErrorResponse())\n\t) {\n\t\tconst flowFrame = snapshotFlowFrame(copyFrameData(record));\n\t\treturn validateFlowFrame(flowFrame);\n\t}\n\tif (typeof type !== \"string\" || type.length === 0) {\n\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t}\n\tif (type === \"ready\") {\n\t\tif (\n\t\t\t!hasOnlyKeys(record, [\"type\", \"protocolVersion\", \"sessionId\", \"pid\"]) ||\n\t\t\trecord.protocolVersion !== 1 ||\n\t\t\t!isNonemptyBoundedString(record.sessionId, MAX_IDENTIFIER_LENGTH) ||\n\t\t\t!Number.isSafeInteger(record.pid) ||\n\t\t\t(record.pid as number) <= 0\n\t\t) {\n\t\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t\t}\n\t\treturn record as RpcReadyFrame;\n\t}\n\tif (type === \"response\") {\n\t\tif (\n\t\t\t!hasOnlyKeys(record, [\"type\", \"id\", \"command\", \"success\", \"error\", \"data\"]) ||\n\t\t\t(record.id !== undefined && !isNonemptyBoundedString(record.id, MAX_IDENTIFIER_LENGTH)) ||\n\t\t\t!isNonemptyBoundedString(command, MAX_IDENTIFIER_LENGTH) ||\n\t\t\ttypeof success !== \"boolean\" ||\n\t\t\t(record.error !== undefined && !isBoundedString(record.error, MAX_ERROR_LENGTH))\n\t\t) {\n\t\t\tthrow new Error(\"Invalid HUMAIN Code CLI RPC frame\");\n\t\t}\n\t\treturn record as RpcResponseFrame;\n\t}\n\treturn frame as RpcNativeEventFrame;\n}\n\n/**\n * Reads optional subagent progress metadata. Absent field means unsupported/unavailable\n * (returns undefined); a present field is strictly parsed and throws when invalid.\n * Update/end piggyback envelopes must carry exactly one run (0 or 2+ throws); get_state accepts 0..64 runs.\n * No other frame fields are inspected or validated.\n */\nexport function readRpcSubagentProgress(frame: RpcWireFrame): SubagentProgressSnapshot | undefined {\n\ttry {\n\t\treturn extractRpcSubagentProgress(frame);\n\t} catch {\n\t\tthrow new Error(INVALID_PROGRESS_MESSAGE);\n\t}\n}\n\nconst INVALID_PROGRESS_MESSAGE = \"Invalid subagent progress snapshot\";\n\n/** Own data property lookup: never invokes getters; `inherited` is true when only a non-own property exists. */\nfunction readOwnData(target: object, key: string): { found: boolean; value?: unknown; inherited: boolean } {\n\tconst descriptor = Object.getOwnPropertyDescriptor(target, key);\n\tif (descriptor === undefined) return { found: false, inherited: key in target };\n\tif (!(\"value\" in descriptor)) throw new Error(INVALID_PROGRESS_MESSAGE);\n\treturn { found: true, value: descriptor.value, inherited: false };\n}\n\nfunction extractRpcSubagentProgress(frame: RpcWireFrame): SubagentProgressSnapshot | undefined {\n\tif (!isRecord(frame)) return undefined;\n\tconst type = readOwnData(frame, \"type\").value;\n\tlet carrier: unknown;\n\tlet singleRun = false;\n\tif (type === \"tool_execution_update\" || type === \"tool_execution_end\") {\n\t\tcarrier = frame;\n\t\tsingleRun = true;\n\t} else if (type === \"response\") {\n\t\tif (readOwnData(frame, \"command\").value !== \"get_state\" || readOwnData(frame, \"success\").value !== true) {\n\t\t\treturn undefined;\n\t\t}\n\t\tcarrier = readOwnData(frame, \"data\").value;\n\t} else {\n\t\treturn undefined;\n\t}\n\tif (!isRecord(carrier)) return undefined;\n\tconst field = readOwnData(carrier, SUBAGENT_PROGRESS_FIELD);\n\tif (field.inherited) throw new Error(INVALID_PROGRESS_MESSAGE);\n\tif (!field.found) return undefined;\n\tconst snapshot = parseSubagentProgressSnapshot(field.value);\n\tif (singleRun && snapshot.runs.length !== 1) throw new Error(INVALID_PROGRESS_MESSAGE);\n\treturn snapshot;\n}\n\nfunction isRpcWireCommand(value: unknown): value is RpcWireCommand {\n\tif (!isRecord(value)) return false;\n\tswitch (value.type) {\n\t\tcase \"prompt\":\n\t\t\treturn (\n\t\t\t\thasOnlyKeys(value, [\"id\", \"type\", \"message\"]) &&\n\t\t\t\tisNonemptyBoundedString(value.id, MAX_IDENTIFIER_LENGTH) &&\n\t\t\t\tisNonemptyBoundedString(value.message, MAX_MESSAGE_LENGTH)\n\t\t\t);\n\t\tcase \"abort\":\n\t\tcase \"get_state\":\n\t\t\treturn hasOnlyKeys(value, [\"id\", \"type\"]) && isNonemptyBoundedString(value.id, MAX_IDENTIFIER_LENGTH);\n\t\tcase \"set_model\":\n\t\t\treturn (\n\t\t\t\thasOnlyKeys(value, [\"type\", \"provider\", \"modelId\"]) &&\n\t\t\t\tisNonemptyBoundedString(value.provider, MAX_IDENTIFIER_LENGTH) &&\n\t\t\t\tisNonemptyBoundedString(value.modelId, MAX_IDENTIFIER_LENGTH)\n\t\t\t);\n\t\tcase \"switch_session\":\n\t\t\treturn (\n\t\t\t\thasOnlyKeys(value, [\"id\", \"type\", \"sessionPath\"]) &&\n\t\t\t\tisNonemptyBoundedString(value.id, MAX_IDENTIFIER_LENGTH) &&\n\t\t\t\tisNonemptyBoundedString(value.sessionPath, MAX_SESSION_PATH_LENGTH)\n\t\t\t);\n\t\tcase \"flow_status\":\n\t\t\treturn (\n\t\t\t\thasExactKeys(value, [\"id\", \"type\"], [\"runId\"]) &&\n\t\t\t\tisFlowId(value.id) &&\n\t\t\t\t(!(\"runId\" in value) || isFlowId(value.runId))\n\t\t\t);\n\t\tcase \"flow_pause\":\n\t\tcase \"flow_resume\":\n\t\t\treturn hasExactKeys(value, [\"id\", \"type\", \"runId\"], []) && isFlowId(value.id) && isFlowId(value.runId);\n\t\tcase \"flow_cancel\":\n\t\t\treturn (\n\t\t\t\thasExactKeys(value, [\"id\", \"type\", \"runId\", \"reason\"], []) &&\n\t\t\t\tisFlowId(value.id) &&\n\t\t\t\tisFlowId(value.runId) &&\n\t\t\t\tFLOW_CANCEL_REASONS.includes(value.reason as string)\n\t\t\t);\n\t\tcase \"flow_message\":\n\t\t\treturn (\n\t\t\t\thasExactKeys(value, [\"id\", \"type\", \"runId\", \"messageId\", \"text\"], [\"target\"]) &&\n\t\t\t\tisFlowId(value.id) &&\n\t\t\t\tisFlowId(value.runId) &&\n\t\t\t\tisFlowId(value.messageId) &&\n\t\t\t\tisNonemptyBoundedString(value.text, FLOW_MESSAGE_MAX_LENGTH) &&\n\t\t\t\t(value.target === undefined ||\n\t\t\t\t\tvalue.target === \"lead\" ||\n\t\t\t\t\t(isRecord(value.target) && hasExactKeys(value.target, [\"taskId\"], []) && isFlowId(value.target.taskId)))\n\t\t\t);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction isFlowCommandType(value: unknown): value is FlowCommandType {\n\treturn FLOW_COMMAND_TYPES.includes(value as FlowCommandType);\n}\n\nfunction isFlowId(value: unknown): value is string {\n\treturn typeof value === \"string\" && FLOW_ID_PATTERN.test(value);\n}\n\nfunction hasExactKeys(\n\tvalue: Record<string, unknown>,\n\trequired: readonly string[],\n\toptional: readonly string[],\n): boolean {\n\treturn (\n\t\tObject.keys(value).every((key) => required.includes(key) || optional.includes(key)) &&\n\t\trequired.every((key) => key in value)\n\t);\n}\n\n/** Full receipt validation (state, reason, terminationConfirmed only for cancel, disposition/deliveredTo only for messages). */\nfunction isFlowReceiptFrame(frame: Record<string, unknown>): boolean {\n\tconst message = frame.command === \"flow_message\";\n\tconst cancel = frame.command === \"flow_cancel\";\n\tif (\n\t\t!hasExactKeys(\n\t\t\tframe,\n\t\t\t[\"type\", \"id\", \"command\", \"state\", ...(message ? [\"messageId\", \"disposition\"] : [])],\n\t\t\t[\"reason\", ...(message ? [\"deliveredTo\"] : cancel ? [\"terminationConfirmed\"] : [])],\n\t\t) ||\n\t\tframe.type !== \"response\" ||\n\t\t!isFlowCommandType(frame.command) ||\n\t\t!isFlowId(frame.id) ||\n\t\t!FLOW_RECEIPT_STATES.includes(frame.state as string) ||\n\t\t(frame.reason !== undefined && !FLOW_REASON_CLASSES.includes(frame.reason as string))\n\t) {\n\t\treturn false;\n\t}\n\tif (cancel) return frame.terminationConfirmed === undefined || typeof frame.terminationConfirmed === \"boolean\";\n\tif (!message) return true;\n\tconst delivered = frame.deliveredTo;\n\treturn (\n\t\tisFlowId(frame.messageId) &&\n\t\tFLOW_DISPOSITIONS.includes(frame.disposition as string) &&\n\t\t(delivered === undefined ||\n\t\t\t(isRecord(delivered) &&\n\t\t\t\thasExactKeys(delivered, [\"taskId\", \"role\"], []) &&\n\t\t\t\tisFlowId(delivered.taskId) &&\n\t\t\t\tFLOW_ROLE_NAMES.includes(delivered.role as string)))\n\t);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonemptyBoundedString(value: unknown, maxLength: number): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n}\n\nfunction isBoundedString(value: unknown, maxLength: number): value is string {\n\treturn typeof value === \"string\" && value.length <= maxLength;\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, allowed: readonly string[]): boolean {\n\tconst keys = Object.keys(value);\n\treturn keys.every((key) => allowed.includes(key)) && allowed.every((key) => key in value || isOptionalKey(key));\n}\n\nfunction isOptionalKey(key: string): boolean {\n\treturn key === \"id\" || key === \"error\" || key === \"data\";\n}\n"]}
|