@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.51

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 (146) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +142 -17
  3. package/dist/agents-store.js +7 -3
  4. package/dist/api-only.d.ts +2 -1
  5. package/dist/api-only.js +3 -2
  6. package/dist/capacity.d.ts +50 -0
  7. package/dist/capacity.js +49 -0
  8. package/dist/cli-learning/claude-wire.d.ts +41 -0
  9. package/dist/cli-learning/claude-wire.js +258 -0
  10. package/dist/cli-learning/cli.d.ts +11 -0
  11. package/dist/cli-learning/cli.js +241 -0
  12. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  13. package/dist/cli-learning/codex-worktree.js +119 -0
  14. package/dist/cli-learning/connections.d.ts +62 -0
  15. package/dist/cli-learning/connections.js +87 -0
  16. package/dist/cli-learning/entry.d.ts +1 -0
  17. package/dist/cli-learning/entry.js +4 -0
  18. package/dist/cli-learning/evidence.d.ts +78 -0
  19. package/dist/cli-learning/evidence.js +492 -0
  20. package/dist/cli-learning/hook.d.ts +33 -0
  21. package/dist/cli-learning/hook.js +544 -0
  22. package/dist/cli-learning/install.d.ts +33 -0
  23. package/dist/cli-learning/install.js +335 -0
  24. package/dist/cli-learning/observation-proof.d.ts +14 -0
  25. package/dist/cli-learning/observation-proof.js +10 -0
  26. package/dist/cli-learning/policy.d.ts +48 -0
  27. package/dist/cli-learning/policy.js +363 -0
  28. package/dist/cli-learning/schema.d.ts +16 -0
  29. package/dist/cli-learning/schema.js +27 -0
  30. package/dist/cli-learning/state.d.ts +23 -0
  31. package/dist/cli-learning/state.js +61 -0
  32. package/dist/cli.js +24 -2
  33. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  34. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  35. package/dist/console/index.html +2 -2
  36. package/dist/email/email-faux.d.ts +3 -1
  37. package/dist/email/email-faux.js +3 -2
  38. package/dist/email/routes.js +22 -12
  39. package/dist/harness-install.d.ts +6 -2
  40. package/dist/harness-install.js +40 -8
  41. package/dist/harness.d.ts +1 -1
  42. package/dist/harness.js +2 -2
  43. package/dist/learn/secrets.js +14 -3
  44. package/dist/learning-words.d.ts +1 -1
  45. package/dist/learning-words.js +1 -1
  46. package/dist/mcp-pin-first.js +2 -1
  47. package/dist/mcp-private-hosts.d.ts +24 -3
  48. package/dist/mcp-private-hosts.js +53 -3
  49. package/dist/model-gateway.d.ts +2 -0
  50. package/dist/model-gateway.js +3 -1
  51. package/dist/native/runtimes.d.ts +2 -0
  52. package/dist/native/runtimes.js +2 -0
  53. package/dist/observation/learning.d.ts +32 -0
  54. package/dist/observation/learning.js +66 -0
  55. package/dist/observation/observer.d.ts +8 -1
  56. package/dist/observation/observer.js +89 -9
  57. package/dist/observation/schema.js +12 -4
  58. package/dist/observation/usage-identity.d.ts +9 -0
  59. package/dist/observation/usage-identity.js +11 -0
  60. package/dist/openapi.js +89 -13
  61. package/dist/run-launch.d.ts +14 -0
  62. package/dist/run-launch.js +4 -0
  63. package/dist/run-view.d.ts +2 -0
  64. package/dist/run-view.js +12 -7
  65. package/dist/runner/adapter-loop.js +29 -26
  66. package/dist/runner/adapter-run-spec.js +2 -2
  67. package/dist/runner/beside.d.ts +13 -0
  68. package/dist/runner/beside.js +27 -8
  69. package/dist/runner/cli-run-spec.js +2 -2
  70. package/dist/runner/disk-free.d.ts +44 -0
  71. package/dist/runner/disk-free.js +96 -0
  72. package/dist/runner/feedback-round.d.ts +12 -8
  73. package/dist/runner/feedback-round.js +16 -30
  74. package/dist/runner/harness-loops.js +3 -1
  75. package/dist/runner/journal-kinds.d.ts +1 -1
  76. package/dist/runner/learning-end.js +4 -0
  77. package/dist/runner/main.d.ts +17 -6
  78. package/dist/runner/main.js +187 -45
  79. package/dist/runner/presence.d.ts +11 -2
  80. package/dist/runner/presence.js +31 -3
  81. package/dist/runner/run-child-host.d.ts +12 -15
  82. package/dist/runner/run-child-host.js +46 -108
  83. package/dist/runner/run-errors.js +2 -0
  84. package/dist/runner/runner-check.d.ts +51 -0
  85. package/dist/runner/runner-check.js +206 -0
  86. package/dist/runner/runner-metrics.d.ts +19 -0
  87. package/dist/runner/runner-metrics.js +49 -0
  88. package/dist/runner/runner.d.ts +37 -0
  89. package/dist/runner/runner.js +43 -3
  90. package/dist/runner/sdk-loop.js +34 -22
  91. package/dist/runs-over-store.d.ts +8 -1
  92. package/dist/runs-over-store.js +57 -9
  93. package/dist/sdk/runs.d.ts +22 -2
  94. package/dist/sdk/runs.js +103 -34
  95. package/dist/server.d.ts +3 -0
  96. package/dist/server.js +149 -26
  97. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  98. package/dist/start-switches.js +2 -0
  99. package/dist/stats.d.ts +4 -0
  100. package/dist/stats.js +1 -1
  101. package/dist/store/agent-body.d.ts +12 -0
  102. package/dist/store/agent-body.js +16 -2
  103. package/dist/store/dialect.d.ts +2 -0
  104. package/dist/store/dialect.js +1 -0
  105. package/dist/store/index.d.ts +3 -3
  106. package/dist/store/index.js +2 -2
  107. package/dist/store/postgres/connection.d.ts +5 -2
  108. package/dist/store/postgres/connection.js +19 -7
  109. package/dist/store/postgres/dialect.js +1 -0
  110. package/dist/store/postgres/migrate.d.ts +30 -0
  111. package/dist/store/postgres/migrate.js +72 -5
  112. package/dist/store/postgres/migration-lint.d.ts +8 -0
  113. package/dist/store/postgres/migration-lint.js +119 -0
  114. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  115. package/dist/store/postgres/store.d.ts +8 -3
  116. package/dist/store/postgres/store.js +31 -11
  117. package/dist/store/schema.d.ts +18 -1
  118. package/dist/store/schema.js +33 -2
  119. package/dist/store/sqlite/run-launch.d.ts +9 -1
  120. package/dist/store/sqlite/run-launch.js +44 -0
  121. package/dist/store/sqlite/store.d.ts +17 -0
  122. package/dist/store/sqlite/store.js +87 -10
  123. package/dist/store/store-schema.d.ts +34 -0
  124. package/dist/store/store-schema.js +125 -0
  125. package/dist/store/store.d.ts +53 -1
  126. package/dist/store/store.js +13 -0
  127. package/dist/store-reads/analytics.d.ts +3 -2
  128. package/dist/store-reads/analytics.js +20 -8
  129. package/dist/store-view.d.ts +4 -3
  130. package/dist/store-view.js +11 -7
  131. package/dist/templates.d.ts +3 -2
  132. package/dist/tool-gate.d.ts +4 -2
  133. package/dist/unified-usage.d.ts +24 -0
  134. package/dist/unified-usage.js +400 -0
  135. package/dist/uploads-archil.d.ts +100 -0
  136. package/dist/uploads-archil.js +430 -0
  137. package/dist/uploads.d.ts +55 -1
  138. package/dist/uploads.js +185 -98
  139. package/dist/validate.js +1 -1
  140. package/dist/workspace/archil-disk.d.ts +6 -5
  141. package/dist/workspace/archil-disk.js +27 -12
  142. package/dist/workspace/archil.js +3 -2
  143. package/package.json +10 -10
  144. package/skills/agentrun-serve/SKILL.md +52 -7
  145. package/dist/console/assets/index-D0mr9wfZ.css +0 -1
  146. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -6,6 +6,13 @@
6
6
  // (RFC 1918, 100.64.0.0/10, fc00::/7), still only over https; loopback, link-local (cloud metadata among it, and the
7
7
  // metadata services inside those ranges), unspecified, multicast, broadcast, reserved and this machine's own addresses
8
8
  // stay refused whatever the list says.
9
+ //
10
+ // Above the owner, the operator (AGENTRUN_PRIVATE_HOSTS, read from each process's own environment at each use, so a
11
+ // server and each of its runners hold to their own): unset, the owner's list holds as above (a machine one owner uses);
12
+ // `none`, no owner's list is read and none can be saved, so nothing of an MCP server or a calendar reaches a private
13
+ // network (a runner many customers share, whose private network is the platform's own); or a comma list of ranges
14
+ // (`10.20.0.0/16,fd12:3456::/32`) a listed host's every address must also fall in. A value that is neither is read as
15
+ // `none` (fail closed), and the capabilities' switches show it.
9
16
  import net from "node:net";
10
17
  import os from "node:os";
11
18
  import { invalid } from "./errors.js";
@@ -26,6 +33,37 @@ for (const [base, bits] of [["10.0.0.0", 8], ["172.16.0.0", 12], ["192.168.0.0",
26
33
  ALLOWABLE.addSubnet(base, bits, "ipv4");
27
34
  ALLOWABLE.addSubnet("fc00::", 7, "ipv6");
28
35
  const familyOf = (address) => (net.isIPv6(address) ? "ipv6" : "ipv4");
36
+ /** The operator's bound on the owner's private hosts, read from the environment of the process that dials. */
37
+ export const PRIVATE_HOSTS_ENV = "AGENTRUN_PRIVATE_HOSTS";
38
+ /** The operator's bound as `env` sets it (PRIVATE_HOSTS_ENV). */
39
+ export function privateHostsBound(env = process.env) {
40
+ const raw = env[PRIVATE_HOSTS_ENV]?.trim();
41
+ if (!raw)
42
+ return { mode: "owner" };
43
+ if (raw === "none")
44
+ return { mode: "none" };
45
+ const list = new net.BlockList();
46
+ const ranges = [];
47
+ for (const entry of raw.split(",").map((one) => one.trim()).filter(Boolean)) {
48
+ const match = /^([^/]+)\/(\d{1,3})$/.exec(entry);
49
+ const family = match ? net.isIP(match[1]) : 0;
50
+ const bits = match ? Number(match[2]) : NaN;
51
+ if (!match || family === 0 || bits > (family === 4 ? 32 : 128))
52
+ return { mode: "none", invalid: `${PRIVATE_HOSTS_ENV}: ${entry} is not an address range such as 10.20.0.0/16 (or none); read as none` };
53
+ list.addSubnet(match[1], bits, family === 4 ? "ipv4" : "ipv6");
54
+ ranges.push(entry);
55
+ }
56
+ if (!ranges.length)
57
+ return { mode: "none", invalid: `${PRIVATE_HOSTS_ENV}=${raw} names no range; read as none` };
58
+ return { mode: "ranges", ranges, list };
59
+ }
60
+ /** The bound as the capabilities' switches show it: unset (null), `none`, or the ranges; a value read as none says so. */
61
+ export const privateHostsSwitchValue = (env = process.env) => {
62
+ const bound = privateHostsBound(env);
63
+ return bound.mode === "owner" ? null : bound.mode === "none" ? (bound.invalid ? `none (${bound.invalid})` : "none") : bound.ranges.join(",");
64
+ };
65
+ /** Why an owner's list cannot be saved under the operator's bound, or undefined when it can. */
66
+ export const ownerListRefused = (env = process.env) => privateHostsBound(env).mode === "none" ? `This server's operator allows no private-network host (${PRIVATE_HOSTS_ENV}=none): an MCP server or a calendar is reached on a public address alone.` : undefined;
29
67
  /** The cloud metadata services inside ALLOWABLE (AWS's over IPv6 in fc00::/7, Alibaba Cloud's in 100.64/10): never
30
68
  * allowable whatever the list says. The rest (169.254.169.254 among them) are link-local, outside it already. The same
31
69
  * addresses the computer's egress table refuses (packages/computer/src/docker/egress-table.ts). */
@@ -41,9 +79,14 @@ export function localAddresses() {
41
79
  }
42
80
  /** Whether a private address `address`, which a listed host resolves to, may be dialled: only in ALLOWABLE, and never one
43
81
  * of `own` (this machine's addresses, and this server's own; an IPv4-mapped form is the same address). */
44
- export function privateAllowed(address, own) {
82
+ export function privateAllowed(address, own, env = process.env) {
45
83
  if (!inAllowableRange(address))
46
84
  return false;
85
+ const bound = privateHostsBound(env);
86
+ if (bound.mode === "none")
87
+ return false;
88
+ if (bound.mode === "ranges" && !bound.list.check(address, familyOf(address)))
89
+ return false;
47
90
  const mine = new net.BlockList();
48
91
  for (const one of own)
49
92
  if (net.isIP(one))
@@ -59,7 +102,10 @@ function hostsOf(value) {
59
102
  /** The private-network hosts the owner allows an authorization server, or an MCP server itself (mcp-oauth.ts
60
103
  * mcpServerAt), on: read from the store at each use, so a host removed is refused from the next request on. The one read
61
104
  * of the setting, for the server's sign-in, preview, save and refresh and the runner's token refresh and calls alike. */
62
- export async function privateOAuthHosts(store) {
105
+ export async function privateOAuthHosts(store, env = process.env) {
106
+ // The operator's `none`: the owner's list is not read, so no host of it is allowed anywhere this process dials.
107
+ if (privateHostsBound(env).mode === "none")
108
+ return [];
63
109
  return hostsOf(await store.settings.get(MCP_PRIVATE_HOSTS_KEY));
64
110
  }
65
111
  /** The store.settings key a server keeps its own addresses under at each start (Serve.own: where it listens, and its
@@ -134,13 +180,17 @@ function entryOf(value, field) {
134
180
  }
135
181
  /** A PUT body `{ hosts }` checked: the list as kept (each entry hostKey'd, the first of any repeat kept), or 422 with
136
182
  * every entry that is not a host name or an IP address on a private network, in words. */
137
- export function checkPrivateHosts(body) {
183
+ export function checkPrivateHosts(body, env = process.env) {
138
184
  const issues = unknownFields(body, ["hosts"]);
139
185
  const { hosts } = body;
140
186
  if (!Array.isArray(hosts)) {
141
187
  issues.push({ field: "hosts", reason: hosts === undefined ? "missing" : "wrong_type", message: "hosts is a list of host names or IP addresses (an empty list allows none)." });
142
188
  throw invalid(issues);
143
189
  }
190
+ // Under the operator's `none` only the empty list is saved: an owner's host would never be allowed.
191
+ const refused = hosts.length ? ownerListRefused(env) : undefined;
192
+ if (refused)
193
+ throw invalid([{ field: "hosts", reason: "not_an_option", message: refused }]);
144
194
  if (hosts.length > MAX_PRIVATE_HOSTS)
145
195
  issues.push({ field: "hosts", reason: "too_long", message: `hosts holds at most ${MAX_PRIVATE_HOSTS} hosts; it holds ${hosts.length}.` });
146
196
  const kept = [];
@@ -13,6 +13,8 @@ export declare const GATEWAY_KEY_ROW = "model_gateway.api_key";
13
13
  * `bare`, the part after the provider (AGENT_MODEL_GATEWAY_IDS=bare). The tiers' own models go as saved either way. */
14
14
  export declare const GATEWAY_IDS: readonly ["as_named", "bare"];
15
15
  export type GatewayIds = (typeof GATEWAY_IDS)[number];
16
+ /** Whether a gateway is sent a model id whole or bare: read by the process that sends (a runner, for its runs). */
17
+ export declare const GATEWAY_IDS_ENV = "AGENT_MODEL_GATEWAY_IDS";
16
18
  /** How long the test waits for the gateway, and how many ids it lists. */
17
19
  export declare const TEST_TIMEOUT_MS = 10000;
18
20
  /** The most of the gateway's answer to the test that is read: a list of MAX_LISTED models is far smaller. */
@@ -53,7 +53,9 @@ export const GATEWAY_KEY_ROW = "model_gateway.api_key";
53
53
  export const GATEWAY_IDS = ["as_named", "bare"];
54
54
  /** The variable each tier's model fills, as the environment names it (model.ts TIER_ENV). */
55
55
  const TIER_VARS = { default: "AGENT_MODEL", fast: "AGENT_MODEL_FAST", strong: "AGENT_MODEL_STRONG" };
56
- const IDS_VAR = "AGENT_MODEL_GATEWAY_IDS";
56
+ /** Whether a gateway is sent a model id whole or bare: read by the process that sends (a runner, for its runs). */
57
+ export const GATEWAY_IDS_ENV = "AGENT_MODEL_GATEWAY_IDS";
58
+ const IDS_VAR = GATEWAY_IDS_ENV;
57
59
  const BASE_VAR = "AGENT_MODEL_BASE_URL";
58
60
  /** The longest key and model id taken: a header value, a name. */
59
61
  const MAX_KEY_CHARS = 4096;
@@ -12,6 +12,7 @@ export declare const NATIVE_RUNTIME_FACTS: Readonly<{
12
12
  readonly label: "Claude Code CLI";
13
13
  readonly minimumVersion: "2.1.322";
14
14
  readonly namedSelector: "agent";
15
+ readonly captureRuntime: "claude-code-cli";
15
16
  readonly protocol: "claude-json";
16
17
  readonly authStatus: readonly string[];
17
18
  readonly authStatusJson: true;
@@ -35,6 +36,7 @@ export declare const NATIVE_RUNTIME_FACTS: Readonly<{
35
36
  readonly label: "Codex CLI";
36
37
  readonly minimumVersion: "0.167.2";
37
38
  readonly namedSelector: "profile";
39
+ readonly captureRuntime: "codex-cli";
38
40
  readonly protocol: "codex-json";
39
41
  readonly authStatus: readonly string[];
40
42
  readonly authStatusJson: false;
@@ -1,6 +1,7 @@
1
1
  export const NATIVE_RUNTIME_FACTS = Object.freeze({
2
2
  "claude-code": Object.freeze({
3
3
  binary: "claude", label: "Claude Code CLI", minimumVersion: "2.1.322", namedSelector: "agent",
4
+ captureRuntime: "claude-code-cli",
4
5
  protocol: "claude-json", authStatus: Object.freeze(["auth", "status", "--json"]),
5
6
  authStatusJson: true, loginCommand: "claude auth login",
6
7
  observation: Object.freeze({
@@ -15,6 +16,7 @@ export const NATIVE_RUNTIME_FACTS = Object.freeze({
15
16
  }),
16
17
  codex: Object.freeze({
17
18
  binary: "codex", label: "Codex CLI", minimumVersion: "0.167.2", namedSelector: "profile",
19
+ captureRuntime: "codex-cli",
18
20
  protocol: "codex-json", authStatus: Object.freeze(["login", "status"]),
19
21
  authStatusJson: false, loginCommand: "codex login",
20
22
  observation: Object.freeze({
@@ -0,0 +1,32 @@
1
+ import { CliLearningConnections } from "../cli-learning/connections.js";
2
+ import { type CliLearningObservationScope, type CliLearningReadiness } from "../cli-learning/observation-proof.js";
3
+ import type { Store } from "../store/store.js";
4
+ export type LearningReport = {
5
+ readiness: CliLearningReadiness;
6
+ connection_id?: string;
7
+ native_session_hash?: string;
8
+ proof?: string;
9
+ };
10
+ /** Persist only verified identifiers and the generation that authorized them, never credentials or proofs. */
11
+ export type LearningAssociation = {
12
+ readiness: CliLearningReadiness;
13
+ connection_id?: string;
14
+ native_session_hash?: string;
15
+ generation?: string;
16
+ };
17
+ export type ObservedLearning = {
18
+ state: "on" | "off" | "setup_required" | "unknown" | "unsupported";
19
+ reason: "ready" | "source_setup_required" | "source_unknown" | "delegated_session" | "connection_unavailable" | "server_disabled" | "agent_disabled" | "awaiting_activation";
20
+ agent_id?: string;
21
+ connection_id?: string;
22
+ mode?: "off" | "notes" | "corrections" | "workflows";
23
+ };
24
+ export declare class ObservationLearning {
25
+ private readonly store;
26
+ private readonly connections;
27
+ private readonly enabled;
28
+ constructor(store: Store, connections: CliLearningConnections, enabled?: boolean);
29
+ verify(report: LearningReport, scope: Omit<CliLearningObservationScope, "connection_id" | "readiness" | "native_session_hash">): Promise<LearningAssociation>;
30
+ view(association: LearningAssociation | undefined, runtime: "codex" | "claude-code"): Promise<ObservedLearning>;
31
+ }
32
+ export declare function unboundLearning(readiness?: CliLearningReadiness): ObservedLearning;
@@ -0,0 +1,66 @@
1
+ import { createHash, timingSafeEqual } from "node:crypto";
2
+ import { getAgent } from "../agents-store.js";
3
+ import { cliLearningObservationProof } from "../cli-learning/observation-proof.js";
4
+ import { learnsOf } from "../learning-setting.js";
5
+ import { cliLearningOf, learningSettingForBody } from "../store/agent-body.js";
6
+ export class ObservationLearning {
7
+ store;
8
+ connections;
9
+ enabled;
10
+ constructor(store, connections, enabled = true) {
11
+ this.store = store;
12
+ this.connections = connections;
13
+ this.enabled = enabled;
14
+ }
15
+ async verify(report, scope) {
16
+ if (!report.connection_id)
17
+ return { readiness: report.readiness };
18
+ const row = await this.connections.get(report.connection_id).catch(() => undefined);
19
+ if (!row?.active || row.runtime !== scope.runtime || !report.proof || !report.native_session_hash)
20
+ return { readiness: "unknown" };
21
+ const expected = cliLearningObservationProof(this.connections.token(row), { ...scope, connection_id: row.connection_id, readiness: report.readiness, native_session_hash: report.native_session_hash });
22
+ if (!timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(report.proof, "hex")))
23
+ return { readiness: "unknown" };
24
+ return { readiness: report.readiness, connection_id: row.connection_id, generation: row.generation, native_session_hash: report.native_session_hash };
25
+ }
26
+ async view(association, runtime) {
27
+ const readiness = association?.readiness ?? "unknown";
28
+ if (!association?.connection_id)
29
+ return unboundLearning(readiness);
30
+ const row = await this.connections.get(association.connection_id).catch(() => undefined);
31
+ if (!row?.active || row.generation !== association.generation || row.runtime !== runtime)
32
+ return { state: "unknown", reason: "connection_unavailable" };
33
+ const entry = await getAgent(this.store, row.agent_id);
34
+ const binding = cliLearningOf(entry?.revision?.body);
35
+ if (!entry || entry.agent.archivedAt != null || !binding || binding.connection_id !== row.connection_id || binding.runtime !== runtime || binding.project !== row.project)
36
+ return { state: "unknown", reason: "connection_unavailable" };
37
+ // Source hooks deliver owner corrections; they do not expose a workflow execution bridge.
38
+ const mode = learnsOf(learningSettingForBody(entry.revision.body)) ? "corrections" : "off";
39
+ const linked = { agent_id: row.agent_id, connection_id: row.connection_id, mode };
40
+ if (!this.enabled)
41
+ return { state: "off", reason: "server_disabled", ...linked };
42
+ if (mode === "off")
43
+ return { state: "off", reason: "agent_disabled", ...linked };
44
+ if (readiness !== "ready")
45
+ return { ...unboundLearning(readiness), ...linked };
46
+ let activated = Boolean(association.native_session_hash && row.hook_sessions?.[association.native_session_hash]);
47
+ // Older connections already have a last-window receipt. It proves activation only for that exact
48
+ // native session and current credential generation; another session in the project proves nothing.
49
+ if (!activated && row.last_run_id) {
50
+ const launch = await this.store.runs.launch(row.last_run_id).catch(() => undefined);
51
+ const window = launch?.body?.cli_learning;
52
+ activated = Boolean(window && window.connection_id === row.connection_id && window.connection_generation === row.generation
53
+ && createHash("sha256").update(window.session_id).digest("hex") === association.native_session_hash);
54
+ }
55
+ if (!activated)
56
+ return { state: "unknown", reason: "awaiting_activation", ...linked };
57
+ return { state: "on", reason: "ready", ...linked };
58
+ }
59
+ }
60
+ export function unboundLearning(readiness = "unknown") {
61
+ if (readiness === "setup_required")
62
+ return { state: "setup_required", reason: "source_setup_required" };
63
+ if (readiness === "unsupported")
64
+ return { state: "unsupported", reason: "delegated_session" };
65
+ return { state: "unknown", reason: "source_unknown" };
66
+ }
@@ -1,5 +1,6 @@
1
1
  import type { Store } from "../store/store.js";
2
2
  import { type NativeObservationHarness } from "../native/runtimes.js";
3
+ import { ObservationLearning } from "./learning.js";
3
4
  export declare const MAX_OTLP_PAYLOAD_BYTES = 1048576;
4
5
  type Harness = NativeObservationHarness;
5
6
  type Selection = {
@@ -17,6 +18,10 @@ export declare class ObservationError extends Error {
17
18
  }
18
19
  export declare const observationCapabilities: () => {
19
20
  version: number;
21
+ session_labels: boolean;
22
+ cli_learning: {
23
+ session_association: boolean;
24
+ };
20
25
  ingestion_modes: string[];
21
26
  supported_harnesses: ("codex" | "claude")[];
22
27
  logs_formats: string[];
@@ -25,6 +30,7 @@ export declare const observationCapabilities: () => {
25
30
  max_log_records: number;
26
31
  max_payload_bytes: number;
27
32
  token_usage: {
33
+ polling: boolean;
28
34
  supported_harnesses: ("codex" | "claude")[];
29
35
  model_attribute: string;
30
36
  count_attributes: string[];
@@ -40,7 +46,8 @@ export declare const observationCapabilities: () => {
40
46
  export declare class Observations {
41
47
  readonly store: Store;
42
48
  readonly now: () => number;
43
- constructor(store: Store, now?: () => number);
49
+ private readonly learning?;
50
+ constructor(store: Store, now?: () => number, learning?: ObservationLearning | undefined);
44
51
  private stamp;
45
52
  private rows;
46
53
  private row;
@@ -2,6 +2,8 @@
2
2
  * Observation never launches a run, imports credentials, creates a runnable definition or enables learning. */
3
3
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  import { NATIVE_OBSERVATION_HARNESSES, nativeObservationProtocol } from "../native/runtimes.js";
5
+ import { unboundLearning } from "./learning.js";
6
+ import { usageIdentityOf } from "./usage-identity.js";
5
7
  const PREFIX = "observation.connector.";
6
8
  const DAY = 86_400_000;
7
9
  const OFFLINE = 120_000;
@@ -55,6 +57,13 @@ const uuid = (v) => typeof v === "string" &&
55
57
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
56
58
  const harness = (v) => nativeObservationProtocol(v) !== undefined;
57
59
  const safeInt = (v, min = 0) => typeof v === "number" && Number.isSafeInteger(v) && v >= min;
60
+ /** Explicit native titles only: no conversation previews, paths, controls or obvious credentials. */
61
+ const sessionLabel = (v, max, project = false) => typeof v === "string" && v.length > 0 && v.length <= max && v.trim() === v &&
62
+ !/[\u0000-\u001f\u007f-\u009f\u2028\u2029\p{Cf}\p{Cs}]/u.test(v) &&
63
+ !/\\/.test(v) && !(project && v.includes("/")) &&
64
+ !/(?:^|[\s"'=(])(?:\/\S|~[/\\]|[A-Za-z]:[/\\]|\\\\)/.test(v) &&
65
+ !/\b[a-z][a-z0-9+.-]*:\/\//i.test(v) &&
66
+ !/\bsk[-_]|ghp_|github_pat_|xox[baprs]-|\bBearer\s|AKIA[A-Z0-9]{12,}/i.test(v);
58
67
  const activities = new Set([
59
68
  "unknown",
60
69
  "working",
@@ -145,6 +154,8 @@ function checkMode(row, sources) {
145
154
  }
146
155
  export const observationCapabilities = () => ({
147
156
  version: 1,
157
+ session_labels: true,
158
+ cli_learning: { session_association: true },
148
159
  ingestion_modes: ["polling", "otlp"],
149
160
  supported_harnesses: [...NATIVE_OBSERVATION_HARNESSES],
150
161
  logs_formats: ["json"],
@@ -153,6 +164,7 @@ export const observationCapabilities = () => ({
153
164
  max_log_records: 100,
154
165
  max_payload_bytes: MAX_OTLP_PAYLOAD_BYTES,
155
166
  token_usage: {
167
+ polling: true,
156
168
  supported_harnesses: [...NATIVE_OBSERVATION_HARNESSES],
157
169
  model_attribute: "agentrun.model",
158
170
  count_attributes: COUNTS.map((k) => "agentrun." + k),
@@ -168,9 +180,11 @@ export const observationCapabilities = () => ({
168
180
  export class Observations {
169
181
  store;
170
182
  now;
171
- constructor(store, now = Date.now) {
183
+ learning;
184
+ constructor(store, now = Date.now, learning) {
172
185
  this.store = store;
173
186
  this.now = now;
187
+ this.learning = learning;
174
188
  }
175
189
  stamp() {
176
190
  return new Date(this.now()).toISOString();
@@ -445,9 +459,10 @@ export class Observations {
445
459
  "type",
446
460
  "occurred_at",
447
461
  "metadata",
462
+ "usage",
448
463
  ]);
449
464
  const m = obj(e.metadata);
450
- exact(m, ["harness", "activity"]);
465
+ exact(m, ["harness", "activity", "display_name", "project_name", "cli_learning"]);
451
466
  if (!uuid(e.event_id) ||
452
467
  !id(e.source_id) ||
453
468
  !id(e.external_session_id) ||
@@ -456,10 +471,47 @@ export class Observations {
456
471
  !timestamp(e.occurred_at) ||
457
472
  Date.parse(e.occurred_at) > this.now() + 300_000 ||
458
473
  !harness(m.harness) ||
459
- !activities.has(m.activity))
474
+ !activities.has(m.activity) ||
475
+ (Object.hasOwn(m, "display_name") && !sessionLabel(m.display_name, 120)) ||
476
+ (Object.hasOwn(m, "project_name") && !sessionLabel(m.project_name, 80, true)))
460
477
  refuse(422, "connector_invalid");
478
+ if (Object.hasOwn(m, "cli_learning")) {
479
+ const learning = obj(m.cli_learning);
480
+ exact(learning, ["readiness", "connection_id", "native_session_hash", "proof"]);
481
+ if (!["ready", "setup_required", "unknown", "unsupported"].includes(learning.readiness)
482
+ || (Object.hasOwn(learning, "connection_id") && !id(learning.connection_id))
483
+ || (Object.hasOwn(learning, "proof") && (typeof learning.proof !== "string" || !/^[0-9a-f]{64}$/.test(learning.proof)))
484
+ || (Object.hasOwn(learning, "native_session_hash") && (typeof learning.native_session_hash !== "string" || !/^[0-9a-f]{64}$/.test(learning.native_session_hash)))
485
+ || Object.hasOwn(learning, "connection_id") !== Object.hasOwn(learning, "proof")
486
+ || Object.hasOwn(learning, "connection_id") !== Object.hasOwn(learning, "native_session_hash")
487
+ || (learning.readiness === "ready" && !learning.connection_id))
488
+ refuse(422, "connector_invalid");
489
+ }
490
+ if (Object.hasOwn(e, "usage")) {
491
+ const usage = obj(e.usage);
492
+ exact(usage, ["model", ...COUNTS]);
493
+ if (typeof usage.model !== "string" ||
494
+ !/^[A-Za-z0-9][A-Za-z0-9._:/+\-]{0,127}$/.test(usage.model) ||
495
+ !safeInt(usage.input_tokens) ||
496
+ !safeInt(usage.output_tokens) ||
497
+ COUNTS.some((k) => Object.hasOwn(usage, k) && !safeInt(usage[k])) ||
498
+ (usage.cache_read_tokens ?? 0) + (usage.cache_write_tokens ?? 0) > usage.input_tokens ||
499
+ !Number.isSafeInteger(usage.input_tokens + usage.output_tokens))
500
+ refuse(422, "connector_invalid");
501
+ }
461
502
  return e;
462
503
  });
504
+ // Authenticate the observation scope before looking up any private CLI connection. A stale or forged
505
+ // association cannot attach a profile, but it must not stop otherwise valid activity and usage ingestion.
506
+ await this.authenticate(connectorId, credential);
507
+ for (const event of events) {
508
+ const report = event.metadata.cli_learning;
509
+ if (report)
510
+ event.learning_association = this.learning
511
+ ? await this.learning.verify(report, { connector_id: connectorId, source_id: event.source_id,
512
+ external_session_id: event.external_session_id, runtime: event.metadata.harness === "claude" ? "claude-code" : "codex", sequence: event.sequence })
513
+ : { readiness: report.connection_id ? "unknown" : report.readiness };
514
+ }
463
515
  return this.ingest(connectorId, credential, b.selections_revision, events, "polling");
464
516
  }
465
517
  async ingest(connectorId, credential, revision, events, mode) {
@@ -485,7 +537,8 @@ export class Observations {
485
537
  refuse(403, "connector_source_denied");
486
538
  if (Date.parse(e.occurred_at) < row.receipt_floor)
487
539
  continue;
488
- const request = fingerprint(e), prior = row.receipts[e.event_id];
540
+ const { learning_association, ...reported } = e;
541
+ const request = fingerprint(reported), prior = row.receipts[e.event_id];
489
542
  if (prior) {
490
543
  if (prior.hash !== request)
491
544
  refuse(409, "idempotency_conflict");
@@ -504,6 +557,13 @@ export class Observations {
504
557
  hash([connectorId, e.metadata.harness, e.external_session_id].join(":")).slice(0, 40), old = row.sessions[sessionId];
505
558
  if (!old && Object.keys(row.sessions).length >= MAX_SESSIONS)
506
559
  refuse(429, "connector_session_capacity_exceeded");
560
+ // Historical accounting survives readiness changes and credential revocation. Migrate
561
+ // old verified associations before replacing them, never trust the raw source report.
562
+ const previousIdentity = usageIdentityOf(old?.usage_identity) ?? usageIdentityOf(old?.learning_association);
563
+ const assertedIdentity = usageIdentityOf(learning_association);
564
+ if (previousIdentity && assertedIdentity && previousIdentity.native_session_hash !== assertedIdentity.native_session_hash)
565
+ refuse(409, "connector_session_identity_conflict");
566
+ const usage_identity = previousIdentity ?? assertedIdentity;
507
567
  const at = this.stamp();
508
568
  row.receipts[e.event_id] = {
509
569
  hash: request,
@@ -515,13 +575,21 @@ export class Observations {
515
575
  ? BigInt(e.source_time) >
516
576
  BigInt(old?.source_time ?? String((old?.sequence ?? 0) * 1000))
517
577
  : e.sequence > (old?.sequence ?? 0));
518
- if (!old || (!e.initial_only && newer))
578
+ if (!old || (!e.initial_only && newer)) {
579
+ // Older clients and OTLP activity may omit names. Keep the last accepted
580
+ // labels until a genuinely newer observation explicitly replaces them.
581
+ const display_name = e.metadata.display_name ?? old?.display_name;
582
+ const project_name = e.metadata.project_name ?? old?.project_name;
519
583
  row.sessions[sessionId] = {
520
584
  id: sessionId,
521
585
  source_id: e.source_id,
522
586
  external_session_id: e.external_session_id,
523
587
  harness: e.metadata.harness,
524
588
  activity: e.metadata.activity,
589
+ ...(display_name ? { display_name } : {}),
590
+ ...(project_name ? { project_name } : {}),
591
+ ...(learning_association ? { learning_association } : {}),
592
+ ...(usage_identity ? { usage_identity } : {}),
525
593
  sequence: e.sequence,
526
594
  ingestion_epoch: row.ingestion_epoch ?? 0,
527
595
  ...(e.source_time ? { source_time: e.source_time } : {}),
@@ -531,9 +599,18 @@ export class Observations {
531
599
  updated_at: at,
532
600
  usage_by_day: old?.usage_by_day ?? {},
533
601
  };
534
- if (e.usage) {
602
+ }
603
+ // An older, independently verified receipt can still establish historical identity
604
+ // without changing current activity/readiness or admitting its stale usage again.
605
+ if (usage_identity)
606
+ row.sessions[sessionId].usage_identity = usage_identity;
607
+ // Polling reports durable counter deltas in sequence order. A new UUID must not
608
+ // make a stale sequence count twice; native OTLP requests can legitimately arrive late.
609
+ if (e.usage && (mode === "otlp" || newer)) {
535
610
  const session = row.sessions[sessionId];
536
- const date = at.slice(0, 10);
611
+ const date = mode === "polling"
612
+ ? new Date(e.occurred_at).toISOString().slice(0, 10)
613
+ : at.slice(0, 10);
537
614
  const day = (session.usage_by_day[date] ??= {});
538
615
  const previous = Object.hasOwn(day, e.usage.model)
539
616
  ? day[e.usage.model]
@@ -737,14 +814,14 @@ export class Observations {
737
814
  this.now();
738
815
  const terminal = ["finished", "failed", "stopped"].includes(s.activity);
739
816
  const summary = summaries.get(s.id);
740
- const { usage_by_day, ingestion_epoch, ...shown } = s;
817
+ const { usage_by_day, ingestion_epoch, learning_association, usage_identity, ...shown } = s;
741
818
  sessions.push({
742
819
  ...shown,
743
820
  connector_id: row.id,
744
821
  workspace_id: "local",
745
822
  kind: "connected_session",
746
823
  state: "active",
747
- display_name: `${row.display_name} · ${s.harness === "claude" ? "Claude Code" : "Codex"}`,
824
+ display_name: s.display_name ?? `${s.harness === "claude" ? "Claude Code" : "Codex"} · ${s.external_session_id.slice(-8)}`,
748
825
  reported_activity: s.activity,
749
826
  activity: terminal
750
827
  ? s.activity
@@ -754,6 +831,9 @@ export class Observations {
754
831
  connection_state: connector.connection_state,
755
832
  selection_active: active,
756
833
  observation_only: true,
834
+ learning: this.learning
835
+ ? await this.learning.view(learning_association, s.harness === "claude" ? "claude-code" : "codex")
836
+ : unboundLearning(learning_association?.readiness),
757
837
  models: [...(summary?.models ?? [])],
758
838
  usage: {
759
839
  ...(summary?.usage ?? unavailable()),
@@ -2,7 +2,7 @@
2
2
  import { NATIVE_OBSERVATION_HARNESSES } from "../native/runtimes.js";
3
3
  const text = { type: "string" };
4
4
  const count = { type: "integer", minimum: 0 };
5
- const object = (properties, required = Object.keys(properties)) => ({ type: "object", properties, required });
5
+ const object = (properties, required = Object.keys(properties), optional = []) => ({ type: "object", properties, required: required.filter((key) => !optional.includes(key)) });
6
6
  const usage = object({
7
7
  input_tokens: count,
8
8
  output_tokens: count,
@@ -29,7 +29,7 @@ export const OBSERVATION_PATHS = {
29
29
  get: {
30
30
  operationId: "getObservations",
31
31
  summary: "Read activity and token usage reported by externally running agents",
32
- description: "Observation-only sessions retain the original harness. They are not executable agent definitions and do not enable learning. Tokens include cache in input; absent cache counters are null. Receipts have a seven-day replay window; older source timestamps cannot create activity or usage. Sessions and received-day usage are retained for 90 days. Capacity overflow is explicitly refused. Cross-connector totals outside exact integer range are null with overflow true. CLI ingestion is at /api/v2/control; /api/v2/control/connectors/capabilities advertises the supported wire formats.",
32
+ description: "Observation-only sessions retain the original harness. They are not executable agent definitions and do not enable learning. Learning status may refer to an existing CLI learning profile after a source proves its project/runtime-scoped credential; On also requires an accepted hook window for the exact native session. Profile settings are read live. No credential, proof or source path appears in observations. Tokens include cache in input; absent cache counters are null. Receipts have a seven-day replay window; older source timestamps cannot create activity or usage. Sessions and daily usage are retained for 90 days. Polling token deltas use the source UTC day and strictly increasing session sequences; OTLP usage uses the received UTC day. Capacity overflow is explicitly refused. Cross-connector totals outside exact integer range are null with overflow true. CLI ingestion is at /api/v2/control; /api/v2/control/connectors/capabilities advertises the supported wire formats and token_usage.polling support.",
33
33
  tags: ["Observations"],
34
34
  security: [{ bearer: [] }],
35
35
  "x-agentrun-serve": "observations/1",
@@ -78,7 +78,8 @@ export const OBSERVATION_PATHS = {
78
78
  created_at: text,
79
79
  updated_at: text,
80
80
  sequence: count,
81
- display_name: text,
81
+ display_name: { ...text, description: "Explicit native session title when reported; otherwise the harness and an opaque ID suffix." },
82
+ project_name: { ...text, description: "Optional project basename; never an absolute source path." },
82
83
  models: { type: "array", items: text },
83
84
  usage: {
84
85
  ...usage,
@@ -89,7 +90,14 @@ export const OBSERVATION_PATHS = {
89
90
  required: [...usage.required, "status"],
90
91
  },
91
92
  observation_only: { const: true },
92
- }),
93
+ learning: object({
94
+ state: { enum: ["on", "off", "setup_required", "unknown", "unsupported"] },
95
+ reason: { enum: ["ready", "source_setup_required", "source_unknown", "delegated_session", "connection_unavailable", "server_disabled", "agent_disabled", "awaiting_activation"] },
96
+ agent_id: text,
97
+ connection_id: text,
98
+ mode: { enum: ["off", "notes", "corrections", "workflows"] },
99
+ }, undefined, ["agent_id", "connection_id", "mode"]),
100
+ }, undefined, ["project_name"]),
93
101
  },
94
102
  usage: {
95
103
  ...usage,
@@ -0,0 +1,9 @@
1
+ /** Private historical provenance for one observed session's retained usage. It grants no learning authority. */
2
+ export type UsageIdentity = {
3
+ native_session_hash: string;
4
+ connection_id: string;
5
+ generation: string;
6
+ };
7
+ /** Read a server-verified association or its persisted accounting identity, never a wire report.
8
+ * Only verification adds generation; structural validation here does not authenticate a source. */
9
+ export declare function usageIdentityOf(value: unknown): UsageIdentity | undefined;
@@ -0,0 +1,11 @@
1
+ /** Read a server-verified association or its persisted accounting identity, never a wire report.
2
+ * Only verification adds generation; structural validation here does not authenticate a source. */
3
+ export function usageIdentityOf(value) {
4
+ if (!value || typeof value !== "object" || Array.isArray(value))
5
+ return undefined;
6
+ const { native_session_hash, connection_id, generation } = value;
7
+ return typeof native_session_hash === "string" && /^[a-f0-9]{64}$/.test(native_session_hash)
8
+ && typeof connection_id === "string" && connection_id.length > 0
9
+ && typeof generation === "string" && generation.length > 0
10
+ ? { native_session_hash, connection_id, generation } : undefined;
11
+ }