chainlesschain 0.166.157 → 0.166.160

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.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Reference-counted MCP server ownership.
3
+ *
4
+ * A server can be shared by a parent session and several child tasks. A child
5
+ * releasing its lease must never tear down a server still held by another
6
+ * task. The implementation is transport agnostic and can wrap an existing
7
+ * async shutdown callback.
8
+ */
9
+ export class McpServerHandle {
10
+ constructor(name, { shutdown } = {}) {
11
+ if (!name || typeof name !== "string")
12
+ throw new TypeError("MCP server handle name is required");
13
+ this.name = name;
14
+ this.holders = new Set();
15
+ this.events = [];
16
+ this.closed = false;
17
+ this._shutdown = typeof shutdown === "function" ? shutdown : async () => {};
18
+ }
19
+
20
+ acquire(taskId) {
21
+ if (this.closed) throw new Error(`MCP server "${this.name}" is closed`);
22
+ if (!taskId || typeof taskId !== "string")
23
+ throw new TypeError("MCP server holder taskId is required");
24
+ this.holders.add(taskId);
25
+ this.events.push({ type: "acquired", taskId, at: Date.now() });
26
+ return this;
27
+ }
28
+
29
+ async release(taskId) {
30
+ if (!taskId || !this.holders.has(taskId)) {
31
+ return {
32
+ released: false,
33
+ closed: this.closed,
34
+ holders: this.holders.size,
35
+ };
36
+ }
37
+ this.holders.delete(taskId);
38
+ this.events.push({ type: "released", taskId, at: Date.now() });
39
+ if (this.holders.size > 0 || this.closed)
40
+ return { released: true, closed: false, holders: this.holders.size };
41
+ await this._shutdown();
42
+ this.closed = true;
43
+ this.events.push({ type: "shutdown", at: Date.now() });
44
+ return { released: true, closed: true, holders: 0 };
45
+ }
46
+
47
+ snapshot() {
48
+ return {
49
+ name: this.name,
50
+ holders: [...this.holders],
51
+ holderCount: this.holders.size,
52
+ closed: this.closed,
53
+ events: this.events.map((event) => ({ ...event })),
54
+ };
55
+ }
56
+ }
57
+
58
+ export class McpServerHandleRegistry {
59
+ constructor() {
60
+ this.handles = new Map();
61
+ }
62
+
63
+ get(name) {
64
+ return this.handles.get(name) || null;
65
+ }
66
+
67
+ acquire(name, taskId, options = {}) {
68
+ let handle = this.handles.get(name);
69
+ if (!handle || handle.closed) {
70
+ handle = new McpServerHandle(name, options);
71
+ this.handles.set(name, handle);
72
+ }
73
+ handle.acquire(taskId);
74
+ return handle;
75
+ }
76
+
77
+ async release(name, taskId) {
78
+ const handle = this.handles.get(name);
79
+ if (!handle) return { released: false, closed: false, holders: 0 };
80
+ const result = await handle.release(taskId);
81
+ if (result.closed) this.handles.delete(name);
82
+ return result;
83
+ }
84
+
85
+ list() {
86
+ return [...this.handles.values()].map((handle) => handle.snapshot());
87
+ }
88
+ }
89
+
90
+ export function createMcpServerHandleRegistry() {
91
+ return new McpServerHandleRegistry();
92
+ }
93
+
94
+ export default {
95
+ McpServerHandle,
96
+ McpServerHandleRegistry,
97
+ createMcpServerHandleRegistry,
98
+ };
@@ -24,6 +24,100 @@ const invalid = () =>
24
24
  true,
25
25
  );
26
26
 
27
+ /** Validate an external MCP tool schema before it reaches a provider API. */
28
+ export function validateMcpInputSchema(
29
+ schema,
30
+ { toolName = "unknown", maxBytes = 256 * 1024 } = {},
31
+ ) {
32
+ const errors = [];
33
+ let encoded = "";
34
+ try {
35
+ encoded = JSON.stringify(schema) || "";
36
+ } catch {
37
+ errors.push({
38
+ tool: toolName,
39
+ path: "$",
40
+ code: "SCHEMA_NOT_SERIALIZABLE",
41
+ message: "inputSchema is not JSON-serializable",
42
+ });
43
+ }
44
+ if (encoded.length > maxBytes)
45
+ errors.push({
46
+ tool: toolName,
47
+ path: "$",
48
+ code: "SCHEMA_TOO_LARGE",
49
+ message: `inputSchema exceeds ${maxBytes} bytes`,
50
+ });
51
+ const visit = (value, path = "$", depth = 0) => {
52
+ if (depth > 32) {
53
+ errors.push({
54
+ tool: toolName,
55
+ path,
56
+ code: "SCHEMA_TOO_DEEP",
57
+ message: "inputSchema nesting exceeds 32 levels",
58
+ });
59
+ return;
60
+ }
61
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
62
+ errors.push({
63
+ tool: toolName,
64
+ path,
65
+ code: "SCHEMA_NOT_OBJECT",
66
+ message: "schema nodes must be objects",
67
+ });
68
+ return;
69
+ }
70
+ if (value.type !== undefined && typeof value.type !== "string")
71
+ errors.push({
72
+ tool: toolName,
73
+ path: `${path}.type`,
74
+ code: "SCHEMA_TYPE_INVALID",
75
+ message: "type must be a string",
76
+ });
77
+ if (value.properties !== undefined) {
78
+ if (
79
+ !value.properties ||
80
+ typeof value.properties !== "object" ||
81
+ Array.isArray(value.properties)
82
+ )
83
+ errors.push({
84
+ tool: toolName,
85
+ path: `${path}.properties`,
86
+ code: "SCHEMA_PROPERTIES_INVALID",
87
+ message: "properties must be an object",
88
+ });
89
+ else
90
+ for (const [key, child] of Object.entries(value.properties))
91
+ visit(child, `${path}.properties.${key}`, depth + 1);
92
+ }
93
+ if (
94
+ value.required !== undefined &&
95
+ (!Array.isArray(value.required) ||
96
+ value.required.some((key) => typeof key !== "string"))
97
+ )
98
+ errors.push({
99
+ tool: toolName,
100
+ path: `${path}.required`,
101
+ code: "SCHEMA_REQUIRED_INVALID",
102
+ message: "required must be an array of strings",
103
+ });
104
+ for (const key of ["items", "additionalProperties", "contains", "not"])
105
+ if (value[key] && typeof value[key] === "object")
106
+ visit(value[key], `${path}.${key}`, depth + 1);
107
+ for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"])
108
+ if (Array.isArray(value[key]))
109
+ value[key].forEach((child, index) =>
110
+ visit(child, `${path}.${key}[${index}]`, depth + 1),
111
+ );
112
+ };
113
+ if (errors.length === 0) visit(schema);
114
+ return Object.freeze({
115
+ valid: errors.length === 0,
116
+ toolName,
117
+ errors: Object.freeze(errors),
118
+ });
119
+ }
120
+
27
121
  /** Only the explicit task API advertises Tasks. Ordinary calls cannot silently
28
122
  * create an untracked background operation, and no input/sampling authority is
29
123
  * advertised by this polling transport. */
@@ -13,6 +13,7 @@ import {
13
13
  appendMcpTaskJournalEvent,
14
14
  readMcpTaskJournal,
15
15
  } from "./mcp-task-journal.js";
16
+ import { registerTaskSource } from "./task-record.js";
16
17
 
17
18
  function failure(code, message, details = {}) {
18
19
  return Object.assign(new Error(message), { code, ...details });
@@ -112,6 +113,16 @@ export function createDurableMcpTaskRuntime({
112
113
  );
113
114
  }
114
115
  let secrets = secretStore;
116
+ // Make the session-owned durable tasks visible to the canonical task view
117
+ // while this runtime is alive. The reader is defensive because a session
118
+ // lease can be retired before a status-line refresh races with it.
119
+ registerTaskSource("mcp", () => {
120
+ try {
121
+ return listDurableMcpTasks(sessionId).records;
122
+ } catch {
123
+ return [];
124
+ }
125
+ });
115
126
  const vault = () =>
116
127
  (secrets ||= createSecretStore({
117
128
  service: "com.chainlesschain.mcp-tasks",
@@ -0,0 +1,42 @@
1
+ /** Canonical model selection/fallback decision shared by parent and child tasks. */
2
+ export function normalizeModelDecision(input = {}) {
3
+ return Object.freeze({
4
+ requestedModel: input.requestedModel ?? input.requested ?? null,
5
+ actualModel: input.actualModel ?? input.model ?? null,
6
+ fallbackReason: input.fallbackReason ?? input.reason ?? null,
7
+ provider: input.provider ?? null,
8
+ region: input.region ?? null,
9
+ endpoint: input.endpoint ?? input.baseUrl ?? null,
10
+ });
11
+ }
12
+
13
+ export function inheritModelDecision(parent, child = {}) {
14
+ const base = normalizeModelDecision(parent);
15
+ const next = normalizeModelDecision(child);
16
+ return normalizeModelDecision({
17
+ ...base,
18
+ ...next,
19
+ requestedModel: next.requestedModel ?? base.requestedModel,
20
+ actualModel: next.actualModel ?? base.actualModel,
21
+ provider: next.provider ?? base.provider,
22
+ region: next.region ?? base.region,
23
+ endpoint: next.endpoint ?? base.endpoint,
24
+ fallbackReason: next.fallbackReason ?? base.fallbackReason,
25
+ });
26
+ }
27
+
28
+ export function modelDecisionTaskEvent(taskId, decision, parentTaskId = null) {
29
+ return Object.freeze({
30
+ type: "model_decision",
31
+ taskId: taskId == null ? null : String(taskId),
32
+ parentTaskId: parentTaskId == null ? null : String(parentTaskId),
33
+ modelDecision: normalizeModelDecision(decision),
34
+ at: new Date().toISOString(),
35
+ });
36
+ }
37
+
38
+ export default {
39
+ normalizeModelDecision,
40
+ inheritModelDecision,
41
+ modelDecisionTaskEvent,
42
+ };
@@ -0,0 +1,47 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const PERMISSION_PROFILE_SCHEMA = "chainlesschain.permission-profile/v1";
4
+
5
+ function canonical(value) {
6
+ if (value == null || typeof value !== "object") return JSON.stringify(value);
7
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
8
+ return `{${Object.keys(value)
9
+ .sort()
10
+ .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
11
+ .join(",")}}`;
12
+ }
13
+
14
+ export function permissionProfileDigest(profile = {}) {
15
+ const payload = canonical({ schema: PERMISSION_PROFILE_SCHEMA, profile });
16
+ return `sha256:${createHash("sha256").update(payload).digest("hex")}`;
17
+ }
18
+
19
+ export function snapshotPermissionProfile(
20
+ profile = {},
21
+ { turnId = null } = {},
22
+ ) {
23
+ const snapshot = {
24
+ schema: PERMISSION_PROFILE_SCHEMA,
25
+ turnId: turnId == null ? null : String(turnId),
26
+ profile: structuredClone(profile),
27
+ };
28
+ return Object.freeze({
29
+ ...snapshot,
30
+ digest: permissionProfileDigest(snapshot.profile),
31
+ });
32
+ }
33
+
34
+ export function isPermissionProfileCurrent(snapshot, profile, turnId = null) {
35
+ return Boolean(
36
+ snapshot &&
37
+ snapshot.digest === permissionProfileDigest(profile) &&
38
+ (snapshot.turnId == null || String(turnId) === snapshot.turnId),
39
+ );
40
+ }
41
+
42
+ export default {
43
+ PERMISSION_PROFILE_SCHEMA,
44
+ permissionProfileDigest,
45
+ snapshotPermissionProfile,
46
+ isPermissionProfileCurrent,
47
+ };
@@ -52,6 +52,8 @@ const VSCODE_COMMANDS = [
52
52
  "chainlesschain.session.modelInputs",
53
53
  "chainlesschain.background.agents",
54
54
  "chainlesschain.sessions.workbench",
55
+ "chainlesschain.sessions.fork",
56
+ "chainlesschain.workflows.map",
55
57
  "chainlesschain.automation.center",
56
58
  "chainlesschain.remote.control",
57
59
  "chainlesschain.appServerPilot.status",
@@ -0,0 +1,62 @@
1
+ /** Monotonic remote runner lifecycle timing with bounded hook admission. */
2
+ export class RunnerLifecycleMetrics {
3
+ constructor({ now = () => Date.now(), hookConcurrency = 4 } = {}) {
4
+ this.now = now;
5
+ this.hookConcurrency = Math.max(1, Number(hookConcurrency) || 4);
6
+ this.startedAt = this.now();
7
+ this.marks = new Map();
8
+ this.activeHooks = 0;
9
+ this.queueDepth = 0;
10
+ }
11
+
12
+ mark(stage, at = this.now()) {
13
+ if (!["ordered", "registered", "first-session"].includes(stage))
14
+ throw new Error(`unknown runner lifecycle stage: ${stage}`);
15
+ this.marks.set(stage, Number(at));
16
+ return this;
17
+ }
18
+
19
+ async runHook(hook, ...args) {
20
+ if (typeof hook !== "function")
21
+ throw new TypeError("runner hook is required");
22
+ if (this.activeHooks >= this.hookConcurrency) {
23
+ this.queueDepth += 1;
24
+ await new Promise((resolve) => {
25
+ const poll = () => {
26
+ if (this.activeHooks < this.hookConcurrency) return resolve();
27
+ setTimeout(poll, 0).unref?.();
28
+ };
29
+ poll();
30
+ });
31
+ this.queueDepth = Math.max(0, this.queueDepth - 1);
32
+ }
33
+ this.activeHooks += 1;
34
+ try {
35
+ return await hook(...args);
36
+ } finally {
37
+ this.activeHooks = Math.max(0, this.activeHooks - 1);
38
+ }
39
+ }
40
+
41
+ snapshot() {
42
+ const ordered = this.marks.get("ordered") ?? null;
43
+ const registered = this.marks.get("registered") ?? null;
44
+ const firstSession = this.marks.get("first-session") ?? null;
45
+ return {
46
+ order_to_registered_seconds:
47
+ ordered != null && registered != null
48
+ ? Math.max(0, (registered - ordered) / 1000)
49
+ : null,
50
+ order_to_first_session_seconds:
51
+ ordered != null && firstSession != null
52
+ ? Math.max(0, (firstSession - ordered) / 1000)
53
+ : null,
54
+ stages: { ordered, registered, "first-session": firstSession },
55
+ hookConcurrency: this.hookConcurrency,
56
+ activeHooks: this.activeHooks,
57
+ queueDepth: this.queueDepth,
58
+ };
59
+ }
60
+ }
61
+
62
+ export default { RunnerLifecycleMetrics };
@@ -74,11 +74,21 @@ function buildContext({
74
74
  usedTokens = 0,
75
75
  contextWindow = 0,
76
76
  turn = 0,
77
+ taskState = null,
78
+ approvalsPending = 0,
79
+ mcpErrors = 0,
80
+ contextUsageThreshold,
77
81
  } = {}) {
78
82
  const used = Math.max(0, Number(usedTokens) || 0);
79
83
  const window = Math.max(0, Number(contextWindow) || 0);
80
84
  const pct = window > 0 ? Math.min(100, Math.round((used / window) * 100)) : 0;
81
- return {
85
+ const threshold = Math.max(0, Math.min(100, Number(contextUsageThreshold) || 0));
86
+ const context = { used_tokens: used, window, pct };
87
+ if (contextUsageThreshold !== undefined) {
88
+ context.visible = window > 0 && pct >= threshold;
89
+ context.threshold = threshold;
90
+ }
91
+ const result = {
82
92
  hook_event_name: "Status",
83
93
  session_id: sessionId || null,
84
94
  model: { id: model || null, display_name: model || null },
@@ -88,9 +98,17 @@ function buildContext({
88
98
  project_dir: projectDir || cwd || process.cwd(),
89
99
  },
90
100
  cwd: cwd || process.cwd(),
91
- context: { used_tokens: used, window, pct },
101
+ context,
92
102
  turn: Math.max(0, Number(turn) || 0),
93
103
  };
104
+ if (taskState || Number(approvalsPending) > 0 || Number(mcpErrors) > 0) {
105
+ result.task = {
106
+ state: taskState || null,
107
+ approvals_pending: Math.max(0, Number(approvalsPending) || 0),
108
+ mcp_errors: Math.max(0, Number(mcpErrors) || 0),
109
+ };
110
+ }
111
+ return result;
94
112
  }
95
113
 
96
114
  /** Compact a token count: 950 → "950", 12345 → "12.3k", 1500000 → "1.5M". */
@@ -147,13 +165,18 @@ function renderDefaultStatusLine(context = {}) {
147
165
  const c = context.context || {};
148
166
  const parts = [];
149
167
  if (context.model && context.model.id) parts.push(context.model.id);
150
- if (c.window > 0) {
168
+ if (c.window > 0 && c.visible !== false) {
151
169
  parts.push(
152
170
  `⛁ ${formatTokens(c.used_tokens)}/${formatTokens(c.window)} (${c.pct}%)`,
153
171
  );
154
172
  } else if (c.used_tokens > 0) {
155
173
  parts.push(`⛁ ${formatTokens(c.used_tokens)}`);
156
174
  }
175
+ const task = context.task || {};
176
+ if (task.state) parts.push(`task ${task.state}`);
177
+ if (task.approvals_pending > 0)
178
+ parts.push(`approvals ${task.approvals_pending}`);
179
+ if (task.mcp_errors > 0) parts.push(`mcp errors ${task.mcp_errors}`);
157
180
  if (context.cwd) parts.push(shortenPath(context.cwd));
158
181
  if (context.turn) parts.push(`turn ${context.turn}`);
159
182
  return parts.join(" · ");
@@ -231,10 +254,24 @@ function getStatusLine({
231
254
  columns,
232
255
  rows,
233
256
  runProcess,
257
+ taskState,
258
+ approvalsPending,
259
+ mcpErrors,
260
+ contextUsageThreshold,
234
261
  } = {}) {
235
262
  const config = loadStatusLineConfig({ cwd, settingsFile });
236
263
  if (!config) return null;
237
- const context = buildContext({ sessionId, model, provider, cwd, projectDir });
264
+ const context = buildContext({
265
+ sessionId,
266
+ model,
267
+ provider,
268
+ cwd,
269
+ projectDir,
270
+ taskState,
271
+ approvalsPending,
272
+ mcpErrors,
273
+ contextUsageThreshold,
274
+ });
238
275
  return renderStatusLine(config, context, {
239
276
  cwd,
240
277
  timeout,
@@ -1,5 +1,6 @@
1
1
  import statusLine from "./status-line.cjs";
2
2
  import executionBroker from "./process-execution-broker/index.js";
3
+ import { collectTaskRecords } from "./task-record.js";
3
4
 
4
5
  const brokerRunner = executionBroker.spawnSync.bind(executionBroker);
5
6
 
@@ -12,8 +13,20 @@ export function renderStatusLine(config, context, options = {}) {
12
13
  }
13
14
 
14
15
  export function getStatusLine(options = {}) {
16
+ const records = collectTaskRecords();
17
+ const waiting = records.filter((task) =>
18
+ ["waiting", "input_required", "paused"].includes(task.state),
19
+ );
15
20
  return statusLine.getStatusLine({
16
21
  ...options,
22
+ taskState: options.taskState || (waiting[0]?.state ?? null),
23
+ approvalsPending:
24
+ options.approvalsPending ??
25
+ records.filter((task) => task.waitingOn === "approval").length,
26
+ mcpErrors:
27
+ options.mcpErrors ??
28
+ records.filter((task) => task.source === "mcp" && task.state === "failed")
29
+ .length,
17
30
  runProcess:
18
31
  options.runProcess || statusLine._deps.runProcess || brokerRunner,
19
32
  });
@@ -4,9 +4,9 @@
4
4
  * @module lib/task-list
5
5
  */
6
6
 
7
- import { listBackgroundShellTasks } from "../runtime/agent-core.js";
8
7
  import { formatBackgroundTasks } from "../repl/tasks-status.js";
9
8
  import { logger } from "./logger.js";
9
+ import { collectTaskRecords, taskCounts } from "./task-record.js";
10
10
 
11
11
  /**
12
12
  * List all background tasks
@@ -14,9 +14,14 @@ import { logger } from "./logger.js";
14
14
  * @returns {Promise<Object>} task list result
15
15
  */
16
16
  export async function listTasks(options = {}) {
17
- const tasks = listBackgroundShellTasks();
18
- const active = tasks.filter((t) => t.status === "running");
19
- const completed = tasks.filter((t) => t.status !== "running");
17
+ const tasks = collectTaskRecords(options);
18
+ const counts = taskCounts(tasks);
19
+ const active = tasks.filter((t) =>
20
+ ["running", "pending", "waiting", "input_required", "paused"].includes(
21
+ t.state,
22
+ ),
23
+ );
24
+ const completed = tasks.filter((t) => t.terminal);
20
25
 
21
26
  if (tasks.length === 0) {
22
27
  logger.info("No background tasks");
@@ -24,7 +29,15 @@ export async function listTasks(options = {}) {
24
29
  }
25
30
 
26
31
  if (!options.quiet) {
27
- logger.info(formatBackgroundTasks(tasks));
32
+ const background = tasks
33
+ .filter((task) => task.source === "background-shell")
34
+ .map((task) => ({
35
+ ...task,
36
+ id: task.taskId,
37
+ status: task.state === "completed" ? "exited" : task.state,
38
+ command: task.label || "",
39
+ }));
40
+ if (background.length) logger.info(formatBackgroundTasks(background));
28
41
  }
29
42
 
30
43
  logger.info(
@@ -32,11 +45,13 @@ export async function listTasks(options = {}) {
32
45
  );
33
46
 
34
47
  return {
35
- count: tasks.length,
36
- active: active.length,
37
- completed: completed.length,
48
+ ...counts,
38
49
  tasks,
39
- formatted: formatBackgroundTasks(tasks),
50
+ formatted: formatBackgroundTasks(
51
+ tasks
52
+ .filter((task) => task.source === "background-shell")
53
+ .map((task) => ({ ...task, id: task.taskId, status: task.state })),
54
+ ),
40
55
  };
41
56
  }
42
57
 
@@ -46,8 +61,8 @@ export async function listTasks(options = {}) {
46
61
  * @returns {Object|null}
47
62
  */
48
63
  export function getTask(taskId) {
49
- const tasks = listBackgroundShellTasks();
50
- return tasks.find((t) => t.id === taskId) || null;
64
+ const tasks = collectTaskRecords();
65
+ return tasks.find((t) => t.taskId === taskId) || null;
51
66
  }
52
67
 
53
68
  export default { listTasks, getTask };