@tangle-network/agent-runtime 0.194.0 → 0.195.1

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.
Files changed (93) hide show
  1. package/dist/{activation-BQFIiyUG.js → activation-B4adh0sA.js} +3 -3
  2. package/dist/{activation-BQFIiyUG.js.map → activation-B4adh0sA.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/candidate-execution/index.js +4 -4
  6. package/dist/{candidate-execution-B6CDW-fp.js → candidate-execution-nvqVIMyS.js} +5 -4
  7. package/dist/{candidate-execution-B6CDW-fp.js.map → candidate-execution-nvqVIMyS.js.map} +1 -1
  8. package/dist/{coordination-driver-iSN-m3VX.js → coordination-driver-CuShDjRV.js} +3 -3
  9. package/dist/{coordination-driver-iSN-m3VX.js.map → coordination-driver-CuShDjRV.js.map} +1 -1
  10. package/dist/{delegate-DCC2muUd.js → delegate-CSFC-Kh3.js} +2 -2
  11. package/dist/{delegate-DCC2muUd.js.map → delegate-CSFC-Kh3.js.map} +1 -1
  12. package/dist/durable.d.ts +1 -1
  13. package/dist/durable.js +2 -2
  14. package/dist/{environment-provider-Dr-wfnHg.js → environment-provider-Z1JazbJ1.js} +108 -10
  15. package/dist/environment-provider-Z1JazbJ1.js.map +1 -0
  16. package/dist/environment-provider.js +1 -1
  17. package/dist/{graph-DghidDx5.js → graph-DqPUeri6.js} +3 -3
  18. package/dist/{graph-DghidDx5.js.map → graph-DqPUeri6.js.map} +1 -1
  19. package/dist/graph.d.ts +1 -1
  20. package/dist/graph.js +4 -4
  21. package/dist/{improve-COGzLCiY.d.ts → improve-7VTwse1c.d.ts} +4 -4
  22. package/dist/{improvement-cycle-DeS1ZC5B.js → improvement-cycle-DEbciBTL.js} +20 -6
  23. package/dist/{improvement-cycle-DeS1ZC5B.js.map → improvement-cycle-DEbciBTL.js.map} +1 -1
  24. package/dist/{index-CrBgLCIf.d.ts → index-CVD30soi.d.ts} +2 -2
  25. package/dist/{index-BEPjOPwH.d.ts → index-DNx0nWZH.d.ts} +9 -2
  26. package/dist/index.d.ts +6 -5
  27. package/dist/index.js +72 -26
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +1 -1
  30. package/dist/intelligence.js +7 -6
  31. package/dist/intelligence.js.map +1 -1
  32. package/dist/kernel.d.ts +1 -1
  33. package/dist/kernel.js +9 -9
  34. package/dist/{knowledge-B5okOzBQ.js → knowledge-B0Mrp-XB.js} +7 -17
  35. package/dist/knowledge-B0Mrp-XB.js.map +1 -0
  36. package/dist/knowledge.d.ts +1 -1
  37. package/dist/knowledge.js +1 -1
  38. package/dist/{loop-runner-bin-U1J6x_UF.js → loop-runner-bin-C5K46H0Q.js} +3 -3
  39. package/dist/{loop-runner-bin-U1J6x_UF.js.map → loop-runner-bin-C5K46H0Q.js.map} +1 -1
  40. package/dist/{loop-runner-bin-Clc5IAwu.d.ts → loop-runner-bin-b4585v9Z.d.ts} +2 -2
  41. package/dist/loop-runner-bin.d.ts +1 -1
  42. package/dist/loop-runner-bin.js +1 -1
  43. package/dist/mcp/bin.js +3 -3
  44. package/dist/mcp/index.d.ts +1 -1
  45. package/dist/mcp/index.js +5 -5
  46. package/dist/{prepare-C29kNAon.js → prepare-DDGp0-rW.js} +4 -54
  47. package/dist/prepare-DDGp0-rW.js.map +1 -0
  48. package/dist/profiles.js +454 -1
  49. package/dist/profiles.js.map +1 -1
  50. package/dist/{protected-model-port-CKYND416.js → protected-model-port-DxFN8DLS.js} +3 -2
  51. package/dist/{protected-model-port-CKYND416.js.map → protected-model-port-DxFN8DLS.js.map} +1 -1
  52. package/dist/{protected-redaction--F3v1oo8.js → protected-redaction-wGo44k2K.js} +54 -3
  53. package/dist/protected-redaction-wGo44k2K.js.map +1 -0
  54. package/dist/{provision-supervisor-CRPbnJiB.js → provision-supervisor-chyz0_Aj.js} +4 -4
  55. package/dist/{provision-supervisor-CRPbnJiB.js.map → provision-supervisor-chyz0_Aj.js.map} +1 -1
  56. package/dist/{redact-BOU77QfQ.js → redact-Dv6PeuQz.js} +2 -2
  57. package/dist/{redact-BOU77QfQ.js.map → redact-Dv6PeuQz.js.map} +1 -1
  58. package/dist/{runtime-BVrqSu0-.js → runtime-BZryF6gD.js} +140 -65
  59. package/dist/runtime-BZryF6gD.js.map +1 -0
  60. package/dist/{server-D6XmE1Du.js → server-BorSFmn8.js} +3 -3
  61. package/dist/{server-D6XmE1Du.js.map → server-BorSFmn8.js.map} +1 -1
  62. package/dist/{structural-rollout-BcPXFzVb.js → structural-rollout-pOqANr8Y.js} +23 -10
  63. package/dist/structural-rollout-pOqANr8Y.js.map +1 -0
  64. package/dist/{supervise-C0V3pZXK.js → supervise-BReI5ATC.js} +4 -4
  65. package/dist/{supervise-C0V3pZXK.js.map → supervise-BReI5ATC.js.map} +1 -1
  66. package/dist/testing.d.ts +1 -1
  67. package/dist/testing.js +14 -13
  68. package/dist/testing.js.map +1 -1
  69. package/dist/tui/index.d.ts +1 -1
  70. package/dist/tui/index.js +1 -1
  71. package/dist/{workspace-archive-BCezkeIk.js → workspace-archive-Ybomp7AN.js} +3 -2
  72. package/dist/{workspace-archive-BCezkeIk.js.map → workspace-archive-Ybomp7AN.js.map} +1 -1
  73. package/package.json +4 -4
  74. package/skills/agent-graphs/SKILL.md +28 -123
  75. package/skills/agent-graphs/references/authoring.md +34 -0
  76. package/skills/agent-graphs/references/measurement.md +18 -0
  77. package/skills/build-with-agent-runtime/SKILL.md +31 -117
  78. package/skills/build-with-agent-runtime/references/improvement.md +32 -0
  79. package/skills/codemode/SKILL.md +22 -34
  80. package/skills/codemode/references/runtime-execution.md +14 -0
  81. package/skills/generate-eval/SKILL.md +2 -1
  82. package/skills/loop-writer/SKILL.md +30 -84
  83. package/skills/supervise/SKILL.md +43 -95
  84. package/skills/supervise/references/profile-authoring.md +19 -0
  85. package/dist/environment-provider-Dr-wfnHg.js.map +0 -1
  86. package/dist/knowledge-B5okOzBQ.js.map +0 -1
  87. package/dist/prepare-C29kNAon.js.map +0 -1
  88. package/dist/protected-redaction--F3v1oo8.js.map +0 -1
  89. package/dist/researcher-Cp4JRbFp.js +0 -457
  90. package/dist/researcher-Cp4JRbFp.js.map +0 -1
  91. package/dist/runtime-BVrqSu0-.js.map +0 -1
  92. package/dist/structural-rollout-BcPXFzVb.js.map +0 -1
  93. package/skills/agent-graphs/IMPROVE.md +0 -58
@@ -1 +0,0 @@
1
- {"version":3,"file":"protected-redaction--F3v1oo8.js","names":[],"sources":["../src/candidate-execution/protected-redaction.ts"],"sourcesContent":["import { createHmac, randomBytes } from 'node:crypto'\n\nimport {\n DEFAULT_REDACTION_RULES,\n REDACTION_VERSION,\n type RedactionRule,\n redactString,\n} from '@tangle-network/agent-eval'\n\nexport interface ProtectedRedactionReport {\n version: string\n redactionCount: number\n byRule: Record<string, number>\n}\n\nexport interface ProtectedTraceIdentity {\n readonly runId: string\n readonly tags: Readonly<Record<string, string>>\n}\n\nexport interface ProtectedRecordRedactor {\n record<T>(value: T): T\n query<T>(value: T): T\n identifier(value: string): string\n traceIdentity(trace: ProtectedTraceIdentity): ProtectedTraceIdentity\n report(): ProtectedRedactionReport\n}\n\n/** Create one execution-local namespace for identifiers changed by redaction. */\nexport function createProtectedRecordRedactor(\n protectedValues: readonly string[],\n): ProtectedRecordRedactor {\n const identityKey = randomBytes(32)\n const aggregate: ProtectedRedactionReport = {\n version: REDACTION_VERSION,\n redactionCount: 0,\n byRule: {},\n }\n\n const mergeReport = (report: ProtectedRedactionReport): void => {\n aggregate.version = report.version\n aggregate.redactionCount += report.redactionCount\n for (const [rule, count] of Object.entries(report.byRule)) {\n aggregate.byRule[rule] = (aggregate.byRule[rule] ?? 0) + count\n }\n }\n\n const redactScalar = <T>(value: T, record: boolean): T => {\n const redacted = redactProtectedValue(value, protectedValues)\n if (record) mergeReport(redacted.report)\n return redacted.value\n }\n\n const identifier = (value: string, record: boolean): string => {\n const redacted = redactScalar(value, record)\n if (redacted === value) return value\n const digest = createHmac('sha256', identityKey).update(value).digest('hex')\n return `${redacted}:hmac-sha256:${digest}`\n }\n\n const transform = <T>(value: T, record: boolean): T => {\n const transformed = transformProtectedRecord(\n value,\n undefined,\n record,\n redactScalar,\n identifier,\n ) as T\n assertNoProtectedEvidence(transformed, protectedValues)\n return transformed\n }\n\n return Object.freeze({\n record: <T>(value: T): T => transform(value, true),\n query: <T>(value: T): T => transform(value, false),\n identifier: (value: string): string => identifier(value, false),\n traceIdentity: (trace: ProtectedTraceIdentity): ProtectedTraceIdentity =>\n transform(trace, false),\n report: (): ProtectedRedactionReport => ({\n version: aggregate.version,\n redactionCount: aggregate.redactionCount,\n byRule: { ...aggregate.byRule },\n }),\n })\n}\n\n/** Redact protected values at the first persistence boundary, including object keys and bytes. */\nexport function redactProtectedValue<T>(\n value: T,\n protectedValues: readonly string[],\n): { value: T; report: ProtectedRedactionReport } {\n const report: ProtectedRedactionReport = {\n version: REDACTION_VERSION,\n redactionCount: 0,\n byRule: {},\n }\n const rules = protectedRedactionRules(protectedValues)\n const redacted = redactNode(value, protectedValues, rules, report) as T\n assertNoProtectedEvidence(redacted, protectedValues)\n return { value: redacted, report }\n}\n\nexport function redactProtectedReason(reason: string, protectedValues: readonly string[]): string {\n try {\n return redactProtectedValue(reason, protectedValues).value\n } catch {\n return 'candidate execution failed with a protected error'\n }\n}\n\nexport function assertNoProtectedEvidence(\n value: unknown,\n protectedValues: readonly string[],\n): void {\n if (value instanceof Uint8Array) {\n assertNoProtectedBytes(value, protectedValues)\n return\n }\n if (typeof value === 'string') {\n for (const protectedValue of protectedValueVariants(protectedValues)) {\n if (value.includes(protectedValue)) {\n throw new Error('protected value survived candidate evidence redaction')\n }\n }\n if (decodedBase64ContainsProtectedValue(value, protectedValues)) {\n throw new Error('base64 protected value survived candidate evidence redaction')\n }\n return\n }\n if (Array.isArray(value)) {\n for (const entry of value) assertNoProtectedEvidence(entry, protectedValues)\n return\n }\n if (value && typeof value === 'object') {\n for (const [key, entry] of Object.entries(value)) {\n assertNoProtectedEvidence(key, protectedValues)\n assertNoProtectedEvidence(entry, protectedValues)\n }\n }\n}\n\nexport function assertNoProtectedBytes(\n bytes: Uint8Array,\n protectedValues: readonly string[],\n): void {\n if (containsProtectedBytes(bytes, protectedValues)) {\n throw new Error('protected value survived candidate evidence byte redaction')\n }\n}\n\nfunction redactNode(\n value: unknown,\n protectedValues: readonly string[],\n rules: readonly RedactionRule[],\n report: ProtectedRedactionReport,\n): unknown {\n if (value instanceof Uint8Array) {\n if (containsProtectedBytes(value, protectedValues)) {\n recordRedaction(report, 'candidate-access-binary', 1)\n return Uint8Array.from(Buffer.from('[redacted:candidate-access-binary]', 'utf8'))\n }\n return Uint8Array.from(value)\n }\n if (typeof value === 'string') {\n if (decodedBase64ContainsProtectedValue(value, protectedValues)) {\n recordRedaction(report, 'candidate-access-binary', 1)\n return '[redacted:candidate-access-binary]'\n }\n const redacted = redactString(value, [...rules])\n for (const [rule, count] of Object.entries(redacted.report.byRule)) {\n recordRedaction(report, rule, count)\n }\n return redacted.output\n }\n if (Array.isArray(value)) {\n return value.map((entry) => redactNode(entry, protectedValues, rules, report))\n }\n if (value && typeof value === 'object') {\n const entries: Array<[string, unknown]> = []\n const seenKeys = new Set<string>()\n for (const [key, entry] of Object.entries(value)) {\n const redactedKey = redactNode(key, protectedValues, rules, report)\n if (typeof redactedKey !== 'string' || seenKeys.has(redactedKey)) {\n throw new Error('protected evidence redaction produced an ambiguous object key')\n }\n seenKeys.add(redactedKey)\n entries.push([redactedKey, redactNode(entry, protectedValues, rules, report)])\n }\n return Object.fromEntries(entries)\n }\n return value\n}\n\nfunction transformProtectedRecord(\n value: unknown,\n fieldName: string | undefined,\n record: boolean,\n redactScalar: <T>(value: T, record: boolean) => T,\n redactIdentifier: (value: string, record: boolean) => string,\n): unknown {\n if (value instanceof Uint8Array) return redactScalar(value, record)\n if (typeof value === 'string') {\n return fieldName && isIdentifierFieldName(fieldName)\n ? redactIdentifier(value, record)\n : redactScalar(value, record)\n }\n if (Array.isArray(value)) {\n return value.map((entry) =>\n transformProtectedRecord(entry, fieldName, record, redactScalar, redactIdentifier),\n )\n }\n if (!value || typeof value !== 'object') return value\n\n if (fieldName === 'tags') {\n return transformTagMap(value, record, redactScalar, redactIdentifier)\n }\n if (fieldName === 'tag') {\n return transformTagFilter(value, record, redactScalar, redactIdentifier)\n }\n\n const entries: Array<[string, unknown]> = []\n const seenKeys = new Set<string>()\n for (const [key, entry] of Object.entries(value)) {\n const redactedKey = redactScalar(key, record)\n if (seenKeys.has(redactedKey)) {\n throw new Error('protected evidence redaction produced an ambiguous object key')\n }\n seenKeys.add(redactedKey)\n entries.push([\n redactedKey,\n transformProtectedRecord(entry, key, record, redactScalar, redactIdentifier),\n ])\n }\n return Object.fromEntries(entries)\n}\n\nfunction transformTagMap(\n value: object,\n record: boolean,\n redactScalar: <T>(value: T, record: boolean) => T,\n redactIdentifier: (value: string, record: boolean) => string,\n): Record<string, unknown> {\n const entries: Array<[string, unknown]> = []\n const seenKeys = new Set<string>()\n for (const [key, entry] of Object.entries(value)) {\n const redactedKey = redactIdentifier(key, record)\n if (seenKeys.has(redactedKey)) {\n throw new Error('protected evidence redaction produced an ambiguous trace tag')\n }\n seenKeys.add(redactedKey)\n entries.push([\n redactedKey,\n typeof entry === 'string'\n ? redactIdentifier(entry, record)\n : transformProtectedRecord(entry, key, record, redactScalar, redactIdentifier),\n ])\n }\n return Object.fromEntries(entries)\n}\n\nfunction transformTagFilter(\n value: object,\n record: boolean,\n redactScalar: <T>(value: T, record: boolean) => T,\n redactIdentifier: (value: string, record: boolean) => string,\n): Record<string, unknown> {\n const output: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) {\n const redactedKey = redactScalar(key, record)\n output[redactedKey] =\n (key === 'key' || key === 'value') && typeof entry === 'string'\n ? redactIdentifier(entry, record)\n : transformProtectedRecord(entry, key, record, redactScalar, redactIdentifier)\n }\n return output\n}\n\nfunction isIdentifierFieldName(name: string): boolean {\n return /ids?$/i.test(name)\n}\n\nfunction protectedRedactionRules(protectedValues: readonly string[]): RedactionRule[] {\n const exactRules = protectedValueVariants(protectedValues)\n .sort((left, right) => right.length - left.length || left.localeCompare(right))\n .map((value, index) => ({\n id: `candidate-access-${index}`,\n pattern: new RegExp(escapeRegularExpression(value), 'g'),\n replacement: '[redacted:candidate-access]',\n }))\n return [...exactRules, ...DEFAULT_REDACTION_RULES]\n}\n\nfunction recordRedaction(report: ProtectedRedactionReport, rule: string, count: number): void {\n if (count <= 0) return\n report.redactionCount += count\n report.byRule[rule] = (report.byRule[rule] ?? 0) + count\n}\n\nfunction containsProtectedBytes(bytes: Uint8Array, protectedValues: readonly string[]): boolean {\n const source = Buffer.from(bytes)\n return protectedValueVariants(protectedValues).some((value) =>\n source.includes(Buffer.from(value, 'utf8')),\n )\n}\n\nfunction decodedBase64ContainsProtectedValue(\n value: string,\n protectedValues: readonly string[],\n): boolean {\n if (value.length < 4 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) {\n return false\n }\n try {\n return containsProtectedBytes(Buffer.from(value, 'base64'), protectedValues)\n } catch {\n return false\n }\n}\n\nfunction protectedValueVariants(protectedValues: readonly string[]): string[] {\n const variants = new Set<string>()\n for (const value of normalizedProtectedValues(protectedValues)) {\n variants.add(value)\n variants.add(Buffer.from(value, 'utf8').toString('base64'))\n variants.add(Buffer.from(value, 'utf8').toString('base64url'))\n variants.add(encodeURIComponent(value))\n }\n return [...variants]\n}\n\nfunction normalizedProtectedValues(values: readonly string[]): string[] {\n return [...new Set(values.filter((value) => value.length > 0))]\n}\n\nfunction escapeRegularExpression(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n"],"mappings":";;;;AA6BA,SAAgB,8BACd,iBACyB;CACzB,MAAM,cAAc,YAAY,EAAE;CAClC,MAAM,YAAsC;EAC1C,SAAS;EACT,gBAAgB;EAChB,QAAQ,CAAC;CACX;CAEA,MAAM,eAAe,WAA2C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@
1
- import { i as ConfigError } from "./errors-CDZ8XsVj.js";
2
- import { t as assertExecutableAgentProfile } from "./model-policy-Wf2MxXJ9.js";
3
- import { agentProfileSchema } from "@tangle-network/agent-interface";
4
- //#region src/profiles/researcher.ts
5
- /**
6
- * Opinionated preset for source-grounded research
7
- * tasks. The agent is told to:
8
- * - bound its work to a single `knowledgeNamespace`
9
- * - emit `items[]` carrying provenance + confidence
10
- * - emit `citations[]` linking quotes back to source urls
11
- * - emit `proposedWrites[]` — never call materialize itself
12
- * - describe `gaps` it could not answer
13
- *
14
- * The profile is stateless and agent-agnostic. The caller supplies the exact execution profile;
15
- * this preset adds only the researcher prompt, tools, parser, and validator.
16
- *
17
- * Propose-don't-apply: the profile NEVER writes to the knowledge base.
18
- * It produces `proposedWrites: KnowledgeUpdate[]` in the output. The
19
- * caller (gtm-agent, journey-eval, user) decides whether to feed those
20
- * updates through `applyKnowledgeWriteBlocks` / a KbStore put.
21
- *
22
- * Namespace isolation: every `KnowledgeItem` + `KnowledgeUpdate` in the
23
- * output carries `namespace`. The validator hard-fails when any item
24
- * touches a namespace other than `task.knowledgeNamespace`.
25
- *
26
- * @experimental
27
- */
28
- const DEFAULT_CITATION_DENSITY_MIN = .7;
29
- /** Build a source-grounded researcher profile with output parsing and validation. @experimental */
30
- function researcherProfile(options) {
31
- const base = agentProfileSchema.parse(options.profile);
32
- assertExecutableAgentProfile(base, "researcherProfile");
33
- const name = options.name ?? base.name;
34
- const systemPrompt = options.systemPrompt ?? RESEARCHER_SYSTEM_PROMPT;
35
- const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN;
36
- const profile = {
37
- ...base,
38
- name,
39
- description: base.description ?? "Source-grounded research agent. Propose-don't-apply.",
40
- prompt: {
41
- ...base.prompt,
42
- systemPrompt
43
- },
44
- tools: {
45
- web_search: true,
46
- fs: true,
47
- shell: true,
48
- ...base.tools
49
- },
50
- metadata: {
51
- ...base.metadata,
52
- specialty: "researcher"
53
- }
54
- };
55
- return {
56
- profile,
57
- taskToPrompt: formatResearcherPrompt,
58
- output: { parse: parseResearcherEvents },
59
- validator: options.task ? createResearcherValidator(options.task, { citationDensityMin }) : createResearcherValidator({
60
- question: "",
61
- knowledgeNamespace: ""
62
- }, {
63
- citationDensityMin,
64
- namespaceCheck: false
65
- }),
66
- agentRunSpec: {
67
- name,
68
- profile,
69
- taskToPrompt: formatResearcherPrompt
70
- }
71
- };
72
- }
73
- /**
74
- * Build a fanout topology over multiple harnesses. The kernel round-robins
75
- * `agentRuns` across the N parallel iterations and the `FanoutVote` driver
76
- * picks the highest-scoring valid output.
77
- *
78
- * @experimental
79
- */
80
- function multiHarnessResearcherFanout(options) {
81
- if (options.profiles.length === 0) throw new ConfigError("multiHarnessResearcherFanout: at least one exact profile is required");
82
- const agentRuns = options.profiles.map((profile) => {
83
- const { agentRunSpec } = researcherProfile({ profile });
84
- return agentRunSpec;
85
- });
86
- const { output, validator } = researcherProfile({
87
- profile: options.profiles[0],
88
- citationDensityMin: options.citationDensityMin,
89
- task: options.task
90
- });
91
- return {
92
- agentRuns,
93
- output,
94
- validator,
95
- driver: {
96
- name: "researcher-fanout",
97
- async plan(task, history) {
98
- return history.length === 0 ? Array.from({ length: agentRuns.length }, () => task) : [];
99
- },
100
- decide() {
101
- return "done";
102
- },
103
- describePlan() {
104
- return { kind: "fanout" };
105
- }
106
- }
107
- };
108
- }
109
- /**
110
- * Build a validator that closes over a specific `ResearchTask`'s constraints.
111
- *
112
- * Checks in order:
113
- * 1. Items must be non-empty.
114
- * 2. Every item carries `evidence.length >= 1`.
115
- * 3. Every item + proposedWrite is scoped to `task.knowledgeNamespace`
116
- * (hard-fail on any namespace mismatch — defence in depth for the
117
- * multi-tenant invariant).
118
- * 4. Citation density (citations with quote / items) >= floor.
119
- *
120
- * Aggregate score:
121
- * 0.4 · citation_density
122
- * + 0.2 · source_diversity (distinct sources / max(items, 1))
123
- * + 0.2 · recency_match (mean fraction within `recencyWindow`)
124
- * + 0.2 · (1 − gaps/maxGaps), maxGaps = max(items, 1)
125
- *
126
- * @experimental
127
- */
128
- function createResearcherValidator(task, config = {}) {
129
- const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN;
130
- const namespaceCheck = config.namespaceCheck ?? true;
131
- return { async validate(output) {
132
- const notes = [];
133
- const scores = {};
134
- let pass = true;
135
- if (!Array.isArray(output.items) || output.items.length === 0) {
136
- pass = false;
137
- notes.push("no items");
138
- scores.items = 0;
139
- } else scores.items = 1;
140
- const missingEvidence = (output.items ?? []).filter((item) => !Array.isArray(item.evidence) || item.evidence.length === 0);
141
- if (missingEvidence.length > 0) {
142
- pass = false;
143
- notes.push(`${missingEvidence.length} item(s) without evidence`);
144
- scores.provenance = 0;
145
- } else scores.provenance = 1;
146
- if (namespaceCheck) {
147
- const foreignItems = (output.items ?? []).filter((item) => item.namespace !== task.knowledgeNamespace);
148
- const foreignWrites = (output.proposedWrites ?? []).filter((write) => write.namespace !== task.knowledgeNamespace);
149
- if (foreignItems.length > 0 || foreignWrites.length > 0) {
150
- pass = false;
151
- notes.push(`namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) outside ${task.knowledgeNamespace}`);
152
- scores.namespace = 0;
153
- } else scores.namespace = 1;
154
- }
155
- const itemCount = Math.max(output.items?.length ?? 0, 1);
156
- const citationsWithQuote = (output.citations ?? []).filter((citation) => typeof citation.quote === "string" && citation.quote.length > 0).length;
157
- const citationDensity = Math.min(1, citationsWithQuote / itemCount);
158
- if (citationDensity < citationDensityMin) {
159
- pass = false;
160
- notes.push(`citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`);
161
- }
162
- scores.citation_density = citationDensity;
163
- const sourceSet = /* @__PURE__ */ new Set();
164
- for (const item of output.items ?? []) for (const evidence of item.evidence ?? []) if (evidence.source) sourceSet.add(evidence.source);
165
- scores.source_diversity = Math.min(1, sourceSet.size / itemCount);
166
- scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow);
167
- const maxGaps = itemCount;
168
- const gapCount = output.gaps?.length ?? 0;
169
- scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps);
170
- const score = .4 * scores.citation_density + .2 * scores.source_diversity + .2 * scores.recency_match + .2 * scores.gap_coverage;
171
- const verdict = {
172
- valid: pass,
173
- score: Number.isFinite(score) ? score : 0,
174
- scores
175
- };
176
- if (notes.length > 0) verdict.notes = notes.join("; ");
177
- return verdict;
178
- } };
179
- }
180
- function recencyMatchScore(items, window) {
181
- if (!window || window.since === void 0 && window.until === void 0) return 1;
182
- if (items.length === 0) return 0;
183
- const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY;
184
- const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY;
185
- let hits = 0;
186
- let total = 0;
187
- for (const item of items) for (const evidence of item.evidence ?? []) {
188
- if (typeof evidence.capturedAt !== "number") continue;
189
- total += 1;
190
- if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1;
191
- }
192
- return total === 0 ? 0 : hits / total;
193
- }
194
- /** Built-in source-grounded research contract added to a caller-owned exact profile. */
195
- const RESEARCHER_SYSTEM_PROMPT = [
196
- "You are a research agent. Your job is to answer a research question with",
197
- "source-grounded knowledge items that the caller will choose whether to",
198
- "persist to a multi-tenant knowledge base.",
199
- "",
200
- "Hard rules:",
201
- " 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.",
202
- " Never write to a different namespace.",
203
- " 2. Every item MUST carry at least one evidence entry with a source.",
204
- " A quote + url is strongly preferred; capturedAt is unix ms.",
205
- " 3. You propose writes — you do NOT apply them. The caller decides.",
206
- " 4. Self-report confidence honestly in [0, 1]. Do not inflate.",
207
- " 5. List what you could not answer in `gaps`. Better to admit a gap",
208
- " than fabricate.",
209
- "",
210
- "When you finish, emit a single final structured message of the shape:",
211
- " ```json",
212
- " { \"items\": [{ \"id\": \"...\", \"namespace\": \"...\", \"claim\": \"...\",",
213
- " \"evidence\": [{ \"source\": \"...\", \"quote\": \"...\",",
214
- " \"url\": \"...\", \"capturedAt\": 0 }],",
215
- " \"confidence\": 0.0,",
216
- " \"authoredBy\": { \"kind\": \"agent\", \"id\": \"...\" } }],",
217
- " \"citations\": [{ \"url\": \"...\", \"quote\": \"...\", \"confidence\": 0.0 }],",
218
- " \"proposedWrites\": [{ \"kind\": \"insert\", \"namespace\": \"...\",",
219
- " \"item\": { /* same shape as items[] */ } }],",
220
- " \"gaps\": [\"...\"],",
221
- " \"notes\": \"free-form commentary\" }",
222
- " ```"
223
- ].join("\n");
224
- function formatResearcherPrompt(task) {
225
- const sources = task.sources?.length ? task.sources.join(", ") : "(no preference)";
226
- const window = formatRecencyWindow(task.recencyWindow);
227
- return [
228
- `Question: ${task.question}`,
229
- `Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,
230
- `Scope: ${task.scope ?? "(unspecified)"}`,
231
- `Preferred sources: ${sources}`,
232
- `Recency window: ${window}`,
233
- `Max items: ${task.maxItems ?? "(no cap)"}`,
234
- `Per-item minimum confidence: ${task.minConfidence ?? "(no floor)"}`,
235
- "",
236
- "Produce knowledge items with provenance + citations + proposed writes.",
237
- "List gaps for anything you could not answer. Emit the final JSON",
238
- "result block exactly as instructed."
239
- ].join("\n");
240
- }
241
- function formatRecencyWindow(window) {
242
- if (!window) return "(none)";
243
- return `${window.since ? window.since.toISOString() : "-∞"} .. ${window.until ? window.until.toISOString() : "now"}`;
244
- }
245
- /**
246
- * Walk the event stream and return the last structured `research.result`
247
- * payload. Falls back to scanning text deltas for a fenced JSON block.
248
- */
249
- function parseResearcherEvents(events) {
250
- for (let i = events.length - 1; i >= 0; i -= 1) {
251
- const event = events[i];
252
- if (!event) continue;
253
- const type = String(event.type ?? "");
254
- const data = isRecord(event.data) ? event.data : {};
255
- if (type === "result" || type === "final" || type === "research.result") {
256
- const direct = coerceResearchOutput(data.result ?? data.output ?? data);
257
- const finalText = pickString(data.finalText);
258
- const fenced = finalText ? extractFencedJson(finalText) : void 0;
259
- const fromFinalText = fenced ? coerceResearchOutput(fenced) : void 0;
260
- if (direct && !isEmptyOutput(direct)) return direct;
261
- if (fromFinalText) return fromFinalText;
262
- if (direct) return direct;
263
- }
264
- }
265
- for (let i = events.length - 1; i >= 0; i -= 1) {
266
- const event = events[i];
267
- if (!event) continue;
268
- const data = isRecord(event.data) ? event.data : {};
269
- const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText);
270
- if (!text) continue;
271
- const fenced = extractFencedJson(text);
272
- if (!fenced) continue;
273
- const coerced = coerceResearchOutput(fenced);
274
- if (coerced) return coerced;
275
- }
276
- return {
277
- items: [],
278
- citations: [],
279
- proposedWrites: []
280
- };
281
- }
282
- function isRecord(value) {
283
- return value !== null && typeof value === "object" && !Array.isArray(value);
284
- }
285
- /** A coerced output that carries no items, citations, or proposed writes. */
286
- function isEmptyOutput(o) {
287
- return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0;
288
- }
289
- function pickString(value) {
290
- return typeof value === "string" && value.length > 0 ? value : void 0;
291
- }
292
- function extractFencedJson(text) {
293
- const match = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
294
- if (!match) return void 0;
295
- const body = (match[1] ?? "").trim();
296
- if (!body) return void 0;
297
- try {
298
- return JSON.parse(body);
299
- } catch {
300
- return;
301
- }
302
- }
303
- function coerceResearchOutput(value) {
304
- if (!isRecord(value)) return void 0;
305
- const items = coerceItems(value.items);
306
- const citations = coerceCitations(value.citations);
307
- const proposedWrites = coerceProposedWrites(value.proposedWrites);
308
- if (items === void 0 && citations === void 0 && proposedWrites === void 0) return;
309
- const output = {
310
- items: items ?? [],
311
- citations: citations ?? [],
312
- proposedWrites: proposedWrites ?? []
313
- };
314
- if (Array.isArray(value.gaps)) output.gaps = value.gaps.filter((entry) => typeof entry === "string");
315
- const notes = pickString(value.notes);
316
- if (notes) output.notes = notes;
317
- const known = /* @__PURE__ */ new Set([
318
- "items",
319
- "citations",
320
- "proposedWrites",
321
- "gaps",
322
- "notes"
323
- ]);
324
- const extras = {};
325
- let extrasCount = 0;
326
- for (const [key, val] of Object.entries(value)) {
327
- if (known.has(key)) continue;
328
- extras[key] = val;
329
- extrasCount += 1;
330
- }
331
- if (extrasCount > 0) output.raw = extras;
332
- return output;
333
- }
334
- function coerceItems(value) {
335
- if (!Array.isArray(value)) return void 0;
336
- const out = [];
337
- for (const entry of value) {
338
- if (!isRecord(entry)) continue;
339
- const id = pickString(entry.id);
340
- const namespace = pickString(entry.namespace);
341
- const claim = pickString(entry.claim);
342
- const evidence = coerceEvidence(entry.evidence);
343
- const confidence = toFiniteNumber(entry.confidence);
344
- const authoredBy = coerceAuthoredBy(entry.authoredBy);
345
- if (!id || !namespace || !claim || !authoredBy) continue;
346
- const item = {
347
- id,
348
- namespace,
349
- claim,
350
- evidence,
351
- confidence: clamp01(confidence),
352
- authoredBy
353
- };
354
- if (Array.isArray(entry.supersedes)) item.supersedes = entry.supersedes.filter((s) => typeof s === "string");
355
- const retractedAt = toFiniteNumber(entry.retractedAt);
356
- if (retractedAt > 0) item.retractedAt = retractedAt;
357
- out.push(item);
358
- }
359
- return out;
360
- }
361
- function coerceEvidence(value) {
362
- if (!Array.isArray(value)) return [];
363
- const out = [];
364
- for (const entry of value) {
365
- if (!isRecord(entry)) continue;
366
- const source = pickString(entry.source);
367
- if (!source) continue;
368
- const item = {
369
- source,
370
- capturedAt: toFiniteNumber(entry.capturedAt)
371
- };
372
- const quote = pickString(entry.quote);
373
- if (quote) item.quote = quote;
374
- const url = pickString(entry.url);
375
- if (url) item.url = url;
376
- out.push(item);
377
- }
378
- return out;
379
- }
380
- function coerceAuthoredBy(value) {
381
- if (!isRecord(value)) return void 0;
382
- const kind = value.kind === "human" || value.kind === "agent" ? value.kind : void 0;
383
- const id = pickString(value.id);
384
- if (!kind || !id) return void 0;
385
- return {
386
- kind,
387
- id
388
- };
389
- }
390
- function coerceCitations(value) {
391
- if (!Array.isArray(value)) return void 0;
392
- const out = [];
393
- for (const entry of value) {
394
- if (!isRecord(entry)) continue;
395
- const url = pickString(entry.url);
396
- const quote = pickString(entry.quote);
397
- if (!url || !quote) continue;
398
- out.push({
399
- url,
400
- quote,
401
- confidence: clamp01(toFiniteNumber(entry.confidence))
402
- });
403
- }
404
- return out;
405
- }
406
- function coerceProposedWrites(value) {
407
- if (!Array.isArray(value)) return void 0;
408
- const out = [];
409
- for (const entry of value) {
410
- if (!isRecord(entry)) continue;
411
- const namespace = pickString(entry.namespace);
412
- if (!namespace) continue;
413
- if (entry.kind === "insert") {
414
- const item = coerceItems([entry.item])?.[0];
415
- if (!item) continue;
416
- out.push({
417
- kind: "insert",
418
- namespace,
419
- item
420
- });
421
- } else if (entry.kind === "supersede") {
422
- const previousId = pickString(entry.previousId);
423
- const item = coerceItems([entry.item])?.[0];
424
- if (!previousId || !item) continue;
425
- out.push({
426
- kind: "supersede",
427
- namespace,
428
- previousId,
429
- item
430
- });
431
- } else if (entry.kind === "retract") {
432
- const itemId = pickString(entry.itemId);
433
- const reason = pickString(entry.reason);
434
- if (!itemId || !reason) continue;
435
- out.push({
436
- kind: "retract",
437
- namespace,
438
- itemId,
439
- reason
440
- });
441
- }
442
- }
443
- return out;
444
- }
445
- function toFiniteNumber(value) {
446
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
447
- }
448
- function clamp01(value) {
449
- if (!Number.isFinite(value)) return 0;
450
- if (value < 0) return 0;
451
- if (value > 1) return 1;
452
- return value;
453
- }
454
- //#endregion
455
- export { researcherProfile as i, createResearcherValidator as n, multiHarnessResearcherFanout as r, RESEARCHER_SYSTEM_PROMPT as t };
456
-
457
- //# sourceMappingURL=researcher-Cp4JRbFp.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"researcher-Cp4JRbFp.js","names":[],"sources":["../src/profiles/researcher.ts"],"sourcesContent":["/**\n * Opinionated preset for source-grounded research\n * tasks. The agent is told to:\n * - bound its work to a single `knowledgeNamespace`\n * - emit `items[]` carrying provenance + confidence\n * - emit `citations[]` linking quotes back to source urls\n * - emit `proposedWrites[]` — never call materialize itself\n * - describe `gaps` it could not answer\n *\n * The profile is stateless and agent-agnostic. The caller supplies the exact execution profile;\n * this preset adds only the researcher prompt, tools, parser, and validator.\n *\n * Propose-don't-apply: the profile NEVER writes to the knowledge base.\n * It produces `proposedWrites: KnowledgeUpdate[]` in the output. The\n * caller (gtm-agent, journey-eval, user) decides whether to feed those\n * updates through `applyKnowledgeWriteBlocks` / a KbStore put.\n *\n * Namespace isolation: every `KnowledgeItem` + `KnowledgeUpdate` in the\n * output carries `namespace`. The validator hard-fails when any item\n * touches a namespace other than `task.knowledgeNamespace`.\n *\n * @experimental\n */\n\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { ConfigError } from '../errors'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type {\n AgentRunSpec,\n DefaultVerdict,\n Driver,\n OutputAdapter,\n Validator,\n} from '../runtime/types'\n\n/** Source families a researcher profile may prefer for a task. One owner: the delegation\n * vocabulary (`DelegateResearchArgs.sources`) re-exports this type rather than restating it.\n * @experimental */\nexport type ResearchSource = 'web' | 'corpus' | 'twitter' | 'github' | 'docs'\n\n/** Task contract for a source-grounded research agent. @experimental */\nexport interface ResearchTask {\n /** The research question to answer. */\n question: string\n /** Bound: e.g. \"audience for cpg-founder ICP\". */\n scope?: string\n /** Multi-tenant scope (customer-id, workspace-id). Validator enforces. */\n knowledgeNamespace: string\n sources?: ResearchSource[]\n recencyWindow?: { since?: Date; until?: Date }\n maxItems?: number\n /** Per-item minimum confidence in [0, 1]. Validator scores recall vs this. */\n minConfidence?: number\n}\n\n/**\n * Knowledge item emitted by the researcher.\n *\n * Profile-local type. When agent-knowledge promotes `KnowledgeClaim` →\n * top-level `KnowledgeItem` substrate-wide, these fields collapse 1:1.\n *\n * @experimental\n */\nexport interface KnowledgeItem {\n id: string\n /** Multi-tenant scope. MUST equal `task.knowledgeNamespace`. */\n namespace: string\n /** The factual claim, in the researcher's words. */\n claim: string\n /** Provenance — at least one entry required. */\n evidence: Array<{ source: string; quote?: string; url?: string; capturedAt: number }>\n /** Researcher's self-reported confidence in [0, 1]. */\n confidence: number\n /** Prior item ids this supersedes (chain). */\n supersedes?: string[]\n /** Set if the agent is retracting an earlier item. Unix ms. */\n retractedAt?: number\n authoredBy: { kind: 'human' | 'agent'; id: string }\n}\n\n/**\n * A proposed write to the knowledge base. The profile does NOT apply\n * these — the caller decides.\n *\n * @experimental\n */\nexport type KnowledgeUpdate =\n | { kind: 'insert'; namespace: string; item: KnowledgeItem }\n | { kind: 'supersede'; namespace: string; previousId: string; item: KnowledgeItem }\n | { kind: 'retract'; namespace: string; itemId: string; reason: string }\n\n/**\n * Researcher output. Required fields are typed; optional fields preserve\n * the agent's free-form intelligence (`notes`, `raw`). The validator\n * enforces the typed minimum.\n *\n * @experimental\n */\nexport interface ResearchOutput {\n items: KnowledgeItem[]\n citations: Array<{ url: string; quote: string; confidence: number }>\n proposedWrites: KnowledgeUpdate[]\n gaps?: string[]\n notes?: string\n /** Anything the agent emitted beyond the typed fields. */\n raw?: unknown\n}\n\n/** Options for the source-grounded researcher profile preset. @experimental */\nexport interface ResearcherProfileOptions {\n /** Caller-owned exact harness/provider/model identity. */\n profile: AgentProfile\n /** Custom system prompt replacement. Default = built-in researcher preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `profile.name`. */\n name?: string\n /**\n * Default 0.7. Minimum (citations with quote) / items ratio for `valid=true`.\n * Below this floor, citation_density scores < 1 and the item set is gated.\n */\n citationDensityMin?: number\n}\n\nconst DEFAULT_CITATION_DENSITY_MIN = 0.7\n\n/** Build a source-grounded researcher profile with output parsing and validation. @experimental */\nexport function researcherProfile(options: ResearcherProfileOptions & { task?: ResearchTask }): {\n profile: AgentProfile\n taskToPrompt: (task: ResearchTask) => string\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n agentRunSpec: AgentRunSpec<ResearchTask>\n} {\n const base = agentProfileSchema.parse(options.profile) as AgentProfile\n assertExecutableAgentProfile(base, 'researcherProfile')\n const name = options.name ?? base.name\n const systemPrompt = options.systemPrompt ?? RESEARCHER_SYSTEM_PROMPT\n const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const profile: AgentProfile = {\n ...base,\n name,\n description: base.description ?? \"Source-grounded research agent. Propose-don't-apply.\",\n prompt: { ...base.prompt, systemPrompt },\n tools: { web_search: true, fs: true, shell: true, ...base.tools },\n metadata: { ...base.metadata, specialty: 'researcher' },\n }\n const output: OutputAdapter<ResearchOutput> = { parse: parseResearcherEvents }\n const validator: Validator<ResearchOutput> = options.task\n ? createResearcherValidator(options.task, { citationDensityMin })\n : createResearcherValidator(\n { question: '', knowledgeNamespace: '' },\n { citationDensityMin, namespaceCheck: false },\n )\n const agentRunSpec: AgentRunSpec<ResearchTask> = {\n name,\n profile,\n taskToPrompt: formatResearcherPrompt,\n }\n return { profile, taskToPrompt: formatResearcherPrompt, output, validator, agentRunSpec }\n}\n\n/** @experimental */\nexport interface MultiHarnessResearcherFanoutOptions {\n /** Exact execution profiles, one per parallel researcher. */\n profiles: ReadonlyArray<AgentProfile>\n /** Default citation density floor for the shared validator. */\n citationDensityMin?: number\n /** Optional task — narrows the validator's namespace check. */\n task?: ResearchTask\n}\n\n/**\n * Build a fanout topology over multiple harnesses. The kernel round-robins\n * `agentRuns` across the N parallel iterations and the `FanoutVote` driver\n * picks the highest-scoring valid output.\n *\n * @experimental\n */\nexport function multiHarnessResearcherFanout(options: MultiHarnessResearcherFanoutOptions): {\n agentRuns: AgentRunSpec<ResearchTask>[]\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n driver: Driver<ResearchTask, ResearchOutput, 'done'>\n} {\n if (options.profiles.length === 0) {\n throw new ConfigError('multiHarnessResearcherFanout: at least one exact profile is required')\n }\n const agentRuns = options.profiles.map((profile) => {\n const { agentRunSpec } = researcherProfile({ profile })\n return agentRunSpec\n })\n const { output, validator } = researcherProfile({\n profile: options.profiles[0]!,\n citationDensityMin: options.citationDensityMin,\n task: options.task,\n })\n // Single fanout round across the N harnesses, then stop: the kernel\n // round-robins `agentRuns` over the N branches and selects the winner\n // (best valid score) across all iterations via `defaultSelectWinner`.\n const driver: Driver<ResearchTask, ResearchOutput, 'done'> = {\n name: 'researcher-fanout',\n async plan(task, history) {\n return history.length === 0 ? Array.from({ length: agentRuns.length }, () => task) : []\n },\n // 'done' is a terminal decision in the kernel; the loop finalizes after\n // the single fanout round and selects the winner via `defaultSelectWinner`.\n decide() {\n return 'done'\n },\n describePlan() {\n return { kind: 'fanout' }\n },\n }\n return { agentRuns, output, validator, driver }\n}\n\n/**\n * Build a validator that closes over a specific `ResearchTask`'s constraints.\n *\n * Checks in order:\n * 1. Items must be non-empty.\n * 2. Every item carries `evidence.length >= 1`.\n * 3. Every item + proposedWrite is scoped to `task.knowledgeNamespace`\n * (hard-fail on any namespace mismatch — defence in depth for the\n * multi-tenant invariant).\n * 4. Citation density (citations with quote / items) >= floor.\n *\n * Aggregate score:\n * 0.4 · citation_density\n * + 0.2 · source_diversity (distinct sources / max(items, 1))\n * + 0.2 · recency_match (mean fraction within `recencyWindow`)\n * + 0.2 · (1 − gaps/maxGaps), maxGaps = max(items, 1)\n *\n * @experimental\n */\nexport function createResearcherValidator(\n task: ResearchTask,\n config: { citationDensityMin?: number; namespaceCheck?: boolean } = {},\n): Validator<ResearchOutput> {\n const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const namespaceCheck = config.namespaceCheck ?? true\n return {\n async validate(output) {\n const notes: string[] = []\n const scores: Record<string, number> = {}\n let pass = true\n\n if (!Array.isArray(output.items) || output.items.length === 0) {\n pass = false\n notes.push('no items')\n scores.items = 0\n } else {\n scores.items = 1\n }\n\n const missingEvidence = (output.items ?? []).filter(\n (item) => !Array.isArray(item.evidence) || item.evidence.length === 0,\n )\n if (missingEvidence.length > 0) {\n pass = false\n notes.push(`${missingEvidence.length} item(s) without evidence`)\n scores.provenance = 0\n } else {\n scores.provenance = 1\n }\n\n if (namespaceCheck) {\n const foreignItems = (output.items ?? []).filter(\n (item) => item.namespace !== task.knowledgeNamespace,\n )\n const foreignWrites = (output.proposedWrites ?? []).filter(\n (write) => write.namespace !== task.knowledgeNamespace,\n )\n if (foreignItems.length > 0 || foreignWrites.length > 0) {\n pass = false\n notes.push(\n `namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) ` +\n `outside ${task.knowledgeNamespace}`,\n )\n scores.namespace = 0\n } else {\n scores.namespace = 1\n }\n }\n\n const itemCount = Math.max(output.items?.length ?? 0, 1)\n const citationsWithQuote = (output.citations ?? []).filter(\n (citation) => typeof citation.quote === 'string' && citation.quote.length > 0,\n ).length\n const citationDensity = Math.min(1, citationsWithQuote / itemCount)\n if (citationDensity < citationDensityMin) {\n pass = false\n notes.push(\n `citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`,\n )\n }\n scores.citation_density = citationDensity\n\n const sourceSet = new Set<string>()\n for (const item of output.items ?? []) {\n for (const evidence of item.evidence ?? []) {\n if (evidence.source) sourceSet.add(evidence.source)\n }\n }\n scores.source_diversity = Math.min(1, sourceSet.size / itemCount)\n\n scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow)\n\n const maxGaps = itemCount\n const gapCount = output.gaps?.length ?? 0\n scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps)\n\n const score =\n 0.4 * scores.citation_density +\n 0.2 * scores.source_diversity +\n 0.2 * scores.recency_match +\n 0.2 * scores.gap_coverage\n\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n },\n }\n}\n\nfunction recencyMatchScore(items: KnowledgeItem[], window: ResearchTask['recencyWindow']): number {\n if (!window || (window.since === undefined && window.until === undefined)) return 1\n if (items.length === 0) return 0\n const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY\n const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY\n let hits = 0\n let total = 0\n for (const item of items) {\n for (const evidence of item.evidence ?? []) {\n if (typeof evidence.capturedAt !== 'number') continue\n total += 1\n if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1\n }\n }\n return total === 0 ? 0 : hits / total\n}\n\n/** Built-in source-grounded research contract added to a caller-owned exact profile. */\nexport const RESEARCHER_SYSTEM_PROMPT = [\n 'You are a research agent. Your job is to answer a research question with',\n 'source-grounded knowledge items that the caller will choose whether to',\n 'persist to a multi-tenant knowledge base.',\n '',\n 'Hard rules:',\n \" 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.\",\n ' Never write to a different namespace.',\n ' 2. Every item MUST carry at least one evidence entry with a source.',\n ' A quote + url is strongly preferred; capturedAt is unix ms.',\n ' 3. You propose writes — you do NOT apply them. The caller decides.',\n ' 4. Self-report confidence honestly in [0, 1]. Do not inflate.',\n ' 5. List what you could not answer in `gaps`. Better to admit a gap',\n ' than fabricate.',\n '',\n 'When you finish, emit a single final structured message of the shape:',\n ' ```json',\n ' { \"items\": [{ \"id\": \"...\", \"namespace\": \"...\", \"claim\": \"...\",',\n ' \"evidence\": [{ \"source\": \"...\", \"quote\": \"...\",',\n ' \"url\": \"...\", \"capturedAt\": 0 }],',\n ' \"confidence\": 0.0,',\n ' \"authoredBy\": { \"kind\": \"agent\", \"id\": \"...\" } }],',\n ' \"citations\": [{ \"url\": \"...\", \"quote\": \"...\", \"confidence\": 0.0 }],',\n ' \"proposedWrites\": [{ \"kind\": \"insert\", \"namespace\": \"...\",',\n ' \"item\": { /* same shape as items[] */ } }],',\n ' \"gaps\": [\"...\"],',\n ' \"notes\": \"free-form commentary\" }',\n ' ```',\n].join('\\n')\n\nfunction formatResearcherPrompt(task: ResearchTask): string {\n const sources = task.sources?.length ? task.sources.join(', ') : '(no preference)'\n const window = formatRecencyWindow(task.recencyWindow)\n return [\n `Question: ${task.question}`,\n `Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,\n `Scope: ${task.scope ?? '(unspecified)'}`,\n `Preferred sources: ${sources}`,\n `Recency window: ${window}`,\n `Max items: ${task.maxItems ?? '(no cap)'}`,\n `Per-item minimum confidence: ${task.minConfidence ?? '(no floor)'}`,\n '',\n 'Produce knowledge items with provenance + citations + proposed writes.',\n 'List gaps for anything you could not answer. Emit the final JSON',\n 'result block exactly as instructed.',\n ].join('\\n')\n}\n\nfunction formatRecencyWindow(window: ResearchTask['recencyWindow']): string {\n if (!window) return '(none)'\n const since = window.since ? window.since.toISOString() : '-∞'\n const until = window.until ? window.until.toISOString() : 'now'\n return `${since} .. ${until}`\n}\n\n/**\n * Walk the event stream and return the last structured `research.result`\n * payload. Falls back to scanning text deltas for a fenced JSON block.\n */\nfunction parseResearcherEvents(events: SandboxEvent[]): ResearchOutput {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : {}\n if (type === 'result' || type === 'final' || type === 'research.result') {\n const direct = coerceResearchOutput(data.result ?? data.output ?? data)\n // opencode reports the agent's terminal answer in `finalText` (not result/output).\n // Parse it too, and prefer it when `direct` is an all-empty shape — otherwise an\n // event carrying both `{items:[],citations:[],proposedWrites:[]}` and a rich\n // finalText would silently drop the real answer.\n const finalText = pickString(data.finalText)\n const fenced = finalText ? extractFencedJson(finalText) : undefined\n const fromFinalText = fenced ? coerceResearchOutput(fenced) : undefined\n if (direct && !isEmptyOutput(direct)) return direct\n if (fromFinalText) return fromFinalText\n if (direct) return direct\n }\n }\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const data = isRecord(event.data) ? event.data : {}\n const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText)\n if (!text) continue\n const fenced = extractFencedJson(text)\n if (!fenced) continue\n const coerced = coerceResearchOutput(fenced)\n if (coerced) return coerced\n }\n return { items: [], citations: [], proposedWrites: [] }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** A coerced output that carries no items, citations, or proposed writes. */\nfunction isEmptyOutput(o: ResearchOutput): boolean {\n return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction extractFencedJson(text: string): unknown | undefined {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)\n if (!match) return undefined\n const body = (match[1] ?? '').trim()\n if (!body) return undefined\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction coerceResearchOutput(value: unknown): ResearchOutput | undefined {\n if (!isRecord(value)) return undefined\n const items = coerceItems(value.items)\n const citations = coerceCitations(value.citations)\n const proposedWrites = coerceProposedWrites(value.proposedWrites)\n // Reject completely empty payloads — those signal \"no result block\",\n // not \"a valid empty result\".\n if (items === undefined && citations === undefined && proposedWrites === undefined) {\n return undefined\n }\n const output: ResearchOutput = {\n items: items ?? [],\n citations: citations ?? [],\n proposedWrites: proposedWrites ?? [],\n }\n if (Array.isArray(value.gaps)) {\n output.gaps = value.gaps.filter((entry): entry is string => typeof entry === 'string')\n }\n const notes = pickString(value.notes)\n if (notes) output.notes = notes\n // Preserve any extra fields the agent emitted that don't fit the typed\n // surface — callers can inspect `raw` without forcing them through the\n // typed coercion. We only include `raw` when the agent emitted fields\n // beyond the known set.\n const known = new Set(['items', 'citations', 'proposedWrites', 'gaps', 'notes'])\n const extras: Record<string, unknown> = {}\n let extrasCount = 0\n for (const [key, val] of Object.entries(value)) {\n if (known.has(key)) continue\n extras[key] = val\n extrasCount += 1\n }\n if (extrasCount > 0) output.raw = extras\n return output\n}\n\nfunction coerceItems(value: unknown): KnowledgeItem[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeItem[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const id = pickString(entry.id)\n const namespace = pickString(entry.namespace)\n const claim = pickString(entry.claim)\n const evidence = coerceEvidence(entry.evidence)\n const confidence = toFiniteNumber(entry.confidence)\n const authoredBy = coerceAuthoredBy(entry.authoredBy)\n if (!id || !namespace || !claim || !authoredBy) continue\n const item: KnowledgeItem = {\n id,\n namespace,\n claim,\n evidence,\n confidence: clamp01(confidence),\n authoredBy,\n }\n if (Array.isArray(entry.supersedes)) {\n item.supersedes = entry.supersedes.filter((s): s is string => typeof s === 'string')\n }\n const retractedAt = toFiniteNumber(entry.retractedAt)\n if (retractedAt > 0) item.retractedAt = retractedAt\n out.push(item)\n }\n return out\n}\n\nfunction coerceEvidence(value: unknown): KnowledgeItem['evidence'] {\n if (!Array.isArray(value)) return []\n const out: KnowledgeItem['evidence'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const source = pickString(entry.source)\n if (!source) continue\n const item: KnowledgeItem['evidence'][number] = {\n source,\n capturedAt: toFiniteNumber(entry.capturedAt),\n }\n const quote = pickString(entry.quote)\n if (quote) item.quote = quote\n const url = pickString(entry.url)\n if (url) item.url = url\n out.push(item)\n }\n return out\n}\n\nfunction coerceAuthoredBy(value: unknown): KnowledgeItem['authoredBy'] | undefined {\n if (!isRecord(value)) return undefined\n const kind = value.kind === 'human' || value.kind === 'agent' ? value.kind : undefined\n const id = pickString(value.id)\n if (!kind || !id) return undefined\n return { kind, id }\n}\n\nfunction coerceCitations(value: unknown): ResearchOutput['citations'] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: ResearchOutput['citations'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const url = pickString(entry.url)\n const quote = pickString(entry.quote)\n if (!url || !quote) continue\n out.push({ url, quote, confidence: clamp01(toFiniteNumber(entry.confidence)) })\n }\n return out\n}\n\nfunction coerceProposedWrites(value: unknown): KnowledgeUpdate[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeUpdate[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const namespace = pickString(entry.namespace)\n if (!namespace) continue\n if (entry.kind === 'insert') {\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!item) continue\n out.push({ kind: 'insert', namespace, item })\n } else if (entry.kind === 'supersede') {\n const previousId = pickString(entry.previousId)\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!previousId || !item) continue\n out.push({ kind: 'supersede', namespace, previousId, item })\n } else if (entry.kind === 'retract') {\n const itemId = pickString(entry.itemId)\n const reason = pickString(entry.reason)\n if (!itemId || !reason) continue\n out.push({ kind: 'retract', namespace, itemId, reason })\n }\n }\n return out\n}\n\nfunction toFiniteNumber(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n if (value < 0) return 0\n if (value > 1) return 1\n return value\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HA,MAAM,+BAA+B;;AAGrC,SAAgB,kBAAkB,SAMhC;CACA,MAAM,OAAO,mBAAmB,MAAM,QAAQ,OAAO;CACrD,6BAA6B,MAAM,mBAAmB;CACtD,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAClC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,qBAAqB,QAAQ,sBAAsB;CACzD,MAAM,UAAwB;EAC5B,GAAG;EACH;EACA,aAAa,KAAK,eAAe;EACjC,QAAQ;GAAE,GAAG,KAAK;GAAQ;EAAa;EACvC,OAAO;GAAE,YAAY;GAAM,IAAI;GAAM,OAAO;GAAM,GAAG,KAAK;EAAM;EAChE,UAAU;GAAE,GAAG,KAAK;GAAU,WAAW;EAAa;CACxD;CAaA,OAAO;EAAE;EAAS,cAAc;EAAwB,QAAA,EAZR,OAAO,sBAYM;EAAG,WAXnB,QAAQ,OACjD,0BAA0B,QAAQ,MAAM,EAAE,mBAAmB,CAAC,IAC9D,0BACE;GAA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