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,276 @@
1
+ /**
2
+ * Canonical task projection shared by CLI, status-line and IDE consumers.
3
+ *
4
+ * Adapters deliberately accept plain objects so callers can project tasks
5
+ * owned by another runtime without importing that runtime's storage layer.
6
+ */
7
+ import { listBackgroundShellTasks } from "../runtime/agent-core.js";
8
+ import { AgentScheduleStore } from "./agent-schedule-store.js";
9
+
10
+ export const TASK_SOURCES = Object.freeze([
11
+ "background-shell",
12
+ "mcp",
13
+ "agent",
14
+ "schedule",
15
+ "cowork",
16
+ ]);
17
+
18
+ export const TASK_STATES = Object.freeze([
19
+ "pending",
20
+ "running",
21
+ "waiting",
22
+ "input_required",
23
+ "paused",
24
+ "completed",
25
+ "failed",
26
+ "cancelled",
27
+ "expired",
28
+ "unknown",
29
+ ]);
30
+
31
+ const TERMINAL = new Set(["completed", "failed", "cancelled", "expired"]);
32
+ const SOURCE_READERS = new Map();
33
+
34
+ /** Register a live source reader without coupling it to the projection layer. */
35
+ export function registerTaskSource(source, reader) {
36
+ if (!source || typeof reader !== "function")
37
+ throw new TypeError("task source requires a name and reader function");
38
+ SOURCE_READERS.set(source, reader);
39
+ return () => SOURCE_READERS.delete(source);
40
+ }
41
+
42
+ function first(value, fallback = null) {
43
+ return value === undefined ? fallback : value;
44
+ }
45
+
46
+ function normalizeState(value, fallback = "unknown") {
47
+ const state = String(value || "")
48
+ .trim()
49
+ .toLowerCase();
50
+ if (TASK_STATES.includes(state)) return state;
51
+ if (
52
+ [
53
+ "active",
54
+ "started",
55
+ "in_progress",
56
+ "working",
57
+ "accepted",
58
+ "observed",
59
+ ].includes(state)
60
+ )
61
+ return "running";
62
+ if (
63
+ [
64
+ "done",
65
+ "success",
66
+ "succeeded",
67
+ "exited",
68
+ "fired",
69
+ "matched",
70
+ "exhausted",
71
+ "result_saved",
72
+ ].includes(state)
73
+ )
74
+ return "completed";
75
+ if (["error", "timeout"].includes(state)) return "failed";
76
+ return fallback;
77
+ }
78
+
79
+ function timestamp(value) {
80
+ if (value == null) return null;
81
+ if (value instanceof Date) return value.toISOString();
82
+ if (typeof value === "number" && Number.isFinite(value))
83
+ return new Date(value).toISOString();
84
+ if (typeof value === "string" && Number.isFinite(Date.parse(value)))
85
+ return new Date(value).toISOString();
86
+ return null;
87
+ }
88
+
89
+ function stableId(value, fallback) {
90
+ const id = value?.taskId ?? value?.id ?? value?.executionId ?? fallback;
91
+ return String(id || fallback);
92
+ }
93
+
94
+ /** Convert one source-specific task into the canonical, additive shape. */
95
+ export function toTaskRecord(value, source = "unknown", options = {}) {
96
+ const input = value && typeof value === "object" ? value : {};
97
+ const normalizedSource = TASK_SOURCES.includes(source)
98
+ ? source
99
+ : source || "unknown";
100
+ const state = normalizeState(
101
+ input.state ??
102
+ input.status ??
103
+ input.remoteStatus ??
104
+ input.phase ??
105
+ input.lifecycleState,
106
+ normalizedSource === "schedule" && input.status === "active"
107
+ ? "running"
108
+ : "unknown",
109
+ );
110
+ const createdAt = timestamp(input.createdAt ?? input.created_at);
111
+ const lastEventAt = timestamp(
112
+ input.lastEventAt ??
113
+ input.lastUpdatedAt ??
114
+ input.updatedAt ??
115
+ input.lastHeartbeat ??
116
+ createdAt,
117
+ );
118
+ const endsAt = timestamp(input.endsAt ?? input.expiresAt ?? input.expiryAt);
119
+ const record = {
120
+ taskId: stableId(
121
+ input,
122
+ options.fallbackId || `${normalizedSource}-unknown`,
123
+ ),
124
+ // Legacy aliases keep existing `/tasks` callers working while new
125
+ // consumers use the explicit canonical names below.
126
+ id: stableId(input, options.fallbackId || `${normalizedSource}-unknown`),
127
+ parentTaskId: first(input.parentTaskId ?? input.parentId, null),
128
+ permissionProfileDigest: first(input.permissionProfileDigest, null),
129
+ modelDecision: first(input.modelDecision, null),
130
+ source: normalizedSource,
131
+ state,
132
+ status: state,
133
+ lastEventAt,
134
+ endsAt,
135
+ waitingOn: first(
136
+ input.waitingOn ??
137
+ input.waitingFor ??
138
+ (state === "input_required"
139
+ ? "input"
140
+ : state === "waiting"
141
+ ? "approval"
142
+ : null),
143
+ null,
144
+ ),
145
+ stopPath: first(
146
+ input.stopPath ??
147
+ input.cancelPath ??
148
+ input.stop ??
149
+ (normalizedSource === "background-shell"
150
+ ? `check_shell --kill ${stableId(input, "unknown")}`
151
+ : normalizedSource === "schedule"
152
+ ? `cc agenda cancel ${stableId(input, "unknown")}`
153
+ : null),
154
+ null,
155
+ ),
156
+ label: first(
157
+ input.label ?? input.description ?? input.command ?? input.prompt,
158
+ null,
159
+ ),
160
+ createdAt,
161
+ nextRunAt: timestamp(input.nextRunAt ?? input.nextAt ?? input.dueAt),
162
+ expiresAction: first(input.expiresAction ?? input.onExpire ?? null, null),
163
+ terminal: TERMINAL.has(state),
164
+ rawSource: normalizedSource === "unknown" ? input : undefined,
165
+ };
166
+ if (options.includeRaw === true) record.raw = input;
167
+ return Object.freeze(record);
168
+ }
169
+
170
+ function mapList(values, source, options) {
171
+ return (Array.isArray(values) ? values : []).map((value, index) =>
172
+ toTaskRecord(value, source, {
173
+ ...options,
174
+ fallbackId: `${source}-${index + 1}`,
175
+ }),
176
+ );
177
+ }
178
+
179
+ /**
180
+ * Project all currently known task sources. Unknown source rows are retained
181
+ * when supplied by a caller, which prevents a new runtime from disappearing
182
+ * from the unified view during a rolling upgrade.
183
+ */
184
+ export function collectTaskRecords(options = {}) {
185
+ const now = options.now == null ? Date.now() : Number(options.now);
186
+ let background = options.backgroundTasks;
187
+ if (background === undefined) {
188
+ try {
189
+ background = listBackgroundShellTasks();
190
+ } catch {
191
+ background = [];
192
+ }
193
+ }
194
+ let scheduled = options.scheduledEntries;
195
+ if (scheduled === undefined) {
196
+ try {
197
+ scheduled = new AgentScheduleStore().list();
198
+ } catch {
199
+ scheduled = [];
200
+ }
201
+ }
202
+ const read = (source, supplied) => {
203
+ if (supplied !== undefined) return supplied;
204
+ const reader = SOURCE_READERS.get(source);
205
+ if (!reader) return [];
206
+ try {
207
+ const value = reader();
208
+ return Array.isArray(value) ? value : [];
209
+ } catch {
210
+ return [];
211
+ }
212
+ };
213
+ const sourceRows =
214
+ options.sources && typeof options.sources === "object"
215
+ ? options.sources
216
+ : {};
217
+ const rows = [
218
+ ...mapList(background, "background-shell", options),
219
+ ...mapList(read("mcp", options.mcpTasks ?? sourceRows.mcp), "mcp", options),
220
+ ...mapList(
221
+ read("agent", options.agentTasks ?? sourceRows.agent),
222
+ "agent",
223
+ options,
224
+ ),
225
+ ...mapList(scheduled, "schedule", options),
226
+ ...mapList(
227
+ read("cowork", options.coworkTasks ?? sourceRows.cowork),
228
+ "cowork",
229
+ options,
230
+ ),
231
+ ...mapList(options.unknownTasks ?? sourceRows.unknown, "unknown", options),
232
+ ];
233
+ const handled = new Set(["mcp", "agent", "cowork", "unknown"]);
234
+ for (const [source, values] of Object.entries(sourceRows)) {
235
+ if (
236
+ handled.has(source) ||
237
+ source === "background-shell" ||
238
+ source === "schedule"
239
+ )
240
+ continue;
241
+ rows.push(...mapList(values, source, options));
242
+ }
243
+ const records = rows.map((record) => {
244
+ if (record.endsAt && Date.parse(record.endsAt) <= now && !record.terminal) {
245
+ return Object.freeze({ ...record, state: "expired", terminal: true });
246
+ }
247
+ return record;
248
+ });
249
+ return records.sort((a, b) =>
250
+ String(b.lastEventAt || b.createdAt || "").localeCompare(
251
+ String(a.lastEventAt || a.createdAt || ""),
252
+ ),
253
+ );
254
+ }
255
+
256
+ export function taskCounts(records) {
257
+ const tasks = Array.isArray(records) ? records : [];
258
+ return {
259
+ count: tasks.length,
260
+ active: tasks.filter((task) =>
261
+ ["running", "pending", "waiting", "input_required", "paused"].includes(
262
+ task.state,
263
+ ),
264
+ ).length,
265
+ completed: tasks.filter((task) => task.terminal).length,
266
+ };
267
+ }
268
+
269
+ export default {
270
+ TASK_SOURCES,
271
+ TASK_STATES,
272
+ toTaskRecord,
273
+ collectTaskRecords,
274
+ taskCounts,
275
+ registerTaskSource,
276
+ };
@@ -681,3 +681,19 @@ export function evaluateUnattendedAction(params = {}) {
681
681
  }
682
682
  return { allow: true, reason: "allowlisted" };
683
683
  }
684
+
685
+ /**
686
+ * Explain which assent branch produced a policy decision. This additive
687
+ * projection keeps the historical `{allow, reason}` contract unchanged while
688
+ * making the no-answer fail-closed branch explicit to event consumers.
689
+ */
690
+ export function resolveAssentDecision(params = {}) {
691
+ const verdict = evaluateUnattendedAction(params);
692
+ const decision =
693
+ params.attended === true
694
+ ? "interactive-assent"
695
+ : verdict.allow
696
+ ? "policy-allow"
697
+ : "no-answer";
698
+ return { ...verdict, decision };
699
+ }
@@ -275,6 +275,7 @@ import {
275
275
  createProviderResponseError,
276
276
  } from "../lib/provider-http-error.js";
277
277
  import { buildPermissionDecision } from "../lib/permission-decision.js";
278
+ import { permissionProfileDigest } from "../lib/permission-profile.js";
278
279
  import { resolveSandboxPolicyPath } from "../lib/agent-sandbox.js";
279
280
  import {
280
281
  beginManagedToolCheckpoint,
@@ -2675,8 +2676,14 @@ function snapshotApprovalPolicyAuthority(approvalGate, sessionId) {
2675
2676
  if (snapshot && typeof snapshot.then === "function") {
2676
2677
  throw new TypeError("approval policy snapshot must be synchronous");
2677
2678
  }
2678
- if (snapshot) return snapshot;
2679
- return {
2679
+ if (snapshot) {
2680
+ return {
2681
+ ...snapshot,
2682
+ permissionProfileDigest:
2683
+ snapshot.permissionProfileDigest || permissionProfileDigest(snapshot),
2684
+ };
2685
+ }
2686
+ const legacy = {
2680
2687
  schema: "chainlesschain.approval-policy-authority/v1",
2681
2688
  kind: "legacy-gate",
2682
2689
  sessionId: sessionId ? String(sessionId) : null,
@@ -2684,6 +2691,10 @@ function snapshotApprovalPolicyAuthority(approvalGate, sessionId) {
2684
2691
  hasAuthorizationConsumer:
2685
2692
  approvalGate.hasAuthorizationConsumer?.() === true,
2686
2693
  };
2694
+ return {
2695
+ ...legacy,
2696
+ permissionProfileDigest: permissionProfileDigest(legacy),
2697
+ };
2687
2698
  }
2688
2699
 
2689
2700
  /**