@peer-agent/protocol 0.1.0-rc.3 → 0.1.0-rc.31

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 (65) hide show
  1. package/dist/acceptance-close-gate.d.ts +10 -1
  2. package/dist/acceptance-close-gate.js +12 -0
  3. package/dist/agent-supervision.d.ts +81 -0
  4. package/dist/agent-supervision.js +1 -0
  5. package/dist/attention.d.ts +44 -0
  6. package/dist/attention.js +1 -0
  7. package/dist/bot-access-policy.d.ts +29 -0
  8. package/dist/bot-access-policy.js +1 -0
  9. package/dist/bot-conversation-read.d.ts +25 -0
  10. package/dist/bot-conversation-read.js +9 -0
  11. package/dist/bot-model-selection.d.ts +13 -0
  12. package/dist/bot-model-selection.js +1 -0
  13. package/dist/browser-window.d.ts +48 -0
  14. package/dist/browser-window.js +23 -0
  15. package/dist/capability-admission.d.ts +20 -0
  16. package/dist/capability-admission.js +1 -0
  17. package/dist/delegation-coordination.d.ts +76 -0
  18. package/dist/delegation-coordination.js +1 -0
  19. package/dist/delegation.d.ts +189 -6
  20. package/dist/delegation.js +39 -39
  21. package/dist/document-reference.d.ts +83 -0
  22. package/dist/document-reference.js +1 -0
  23. package/dist/evidence-inspection.d.ts +51 -0
  24. package/dist/evidence-inspection.js +1 -0
  25. package/dist/goal.d.ts +49 -2
  26. package/dist/index.d.ts +46 -5
  27. package/dist/index.js +19 -0
  28. package/dist/local-git.d.ts +44 -0
  29. package/dist/local-git.js +3 -0
  30. package/dist/local-image.d.ts +53 -0
  31. package/dist/local-image.js +5 -0
  32. package/dist/model-reasoning.d.ts +13 -0
  33. package/dist/model-reasoning.js +18 -0
  34. package/dist/model-routing.d.ts +36 -2
  35. package/dist/model-routing.js +30 -5
  36. package/dist/project-agent-failure.d.ts +30 -0
  37. package/dist/project-agent-failure.js +44 -0
  38. package/dist/project-input-recovery.d.ts +65 -0
  39. package/dist/project-input-recovery.js +5 -0
  40. package/dist/project-recovery.d.ts +43 -0
  41. package/dist/project-recovery.js +1 -0
  42. package/dist/project.d.ts +63 -0
  43. package/dist/project.js +2 -5
  44. package/dist/resource-edit-execution.d.ts +68 -0
  45. package/dist/resource-edit-execution.js +96 -0
  46. package/dist/resource-edit.d.ts +237 -0
  47. package/dist/resource-edit.js +134 -0
  48. package/dist/resource-feedback.d.ts +91 -0
  49. package/dist/resource-feedback.js +120 -0
  50. package/dist/resource-file-replace.d.ts +36 -0
  51. package/dist/resource-file-replace.js +40 -0
  52. package/dist/resource-reference-hints.d.ts +3 -0
  53. package/dist/resource-reference-hints.js +58 -0
  54. package/dist/resource-window.d.ts +138 -0
  55. package/dist/resource-window.js +116 -0
  56. package/dist/session-facts.d.ts +29 -0
  57. package/dist/session-facts.js +35 -0
  58. package/dist/system-context.d.ts +6 -0
  59. package/dist/task-overview.d.ts +89 -0
  60. package/dist/task-overview.js +317 -17
  61. package/dist/tool-activity-preview.d.ts +4 -0
  62. package/dist/tool-activity-preview.js +72 -0
  63. package/dist/work-coordination.d.ts +136 -0
  64. package/dist/work-coordination.js +1 -0
  65. package/package.json +1 -1
package/dist/project.d.ts CHANGED
@@ -173,6 +173,7 @@ export interface BotProfile {
173
173
  }
174
174
  export interface BotRowState {
175
175
  readonly needsYou: number;
176
+ readonly attentionExpiresAt?: string;
176
177
  readonly unread: number;
177
178
  readonly running: number;
178
179
  /** Ephemeral status of the runner hosted by this desktop process. */
@@ -189,6 +190,65 @@ export interface BotListFilter {
189
190
  readonly query?: string;
190
191
  readonly needsYouOnly?: boolean;
191
192
  }
193
+ /** Bounded, redacted display preview; never an execution or Evidence object. */
194
+ export interface ProjectAgentToolPreview {
195
+ readonly text: string;
196
+ readonly truncated: boolean;
197
+ readonly redacted: boolean;
198
+ }
199
+ export interface ProjectAgentToolActivity {
200
+ readonly kind: 'tool';
201
+ readonly id: string;
202
+ readonly name: string;
203
+ readonly status: 'preparing' | 'running' | 'awaiting_permission' | 'done' | 'error' | 'stopped';
204
+ readonly startedAt?: string;
205
+ readonly finishedAt?: string;
206
+ readonly summary?: string;
207
+ readonly input?: ProjectAgentToolPreview;
208
+ readonly result?: ProjectAgentToolPreview;
209
+ readonly receivedChars?: number;
210
+ readonly permissionDeadlineAt?: string;
211
+ }
212
+ /** Public conversation update, never hidden reasoning, Tool Result or Evidence.
213
+ * User agent_turn records may persist these as publicUpdates (100 / 32000 chars).
214
+ * Legacy rounds[].text is not a public-update source.
215
+ */
216
+ export interface ProjectAgentPublicUpdate {
217
+ readonly id: string;
218
+ readonly text: string;
219
+ }
220
+ /** Ephemeral interactive-turn presentation, including explicit wake retries. No hidden reasoning or Evidence. */
221
+ export interface ProjectAgentActivity {
222
+ /** Same-turn successful local file results only; navigation hints never grant access. */
223
+ readonly resourceReferences?: readonly import('./document-reference.ts').BotResourceReferenceHint[];
224
+ readonly workspaceId: string;
225
+ readonly conversationId: string;
226
+ readonly turnId: string;
227
+ /** Existing coordination identity; several execution attempts may serve one reply. */
228
+ readonly workId?: string;
229
+ readonly revision: number;
230
+ readonly startedAt: string;
231
+ readonly finishedAt?: string;
232
+ readonly modelSelection?: Pick<import('./model-routing.ts').RuntimeModelSelection, 'modelProviderId' | 'reasoningEffort'>;
233
+ readonly replyTo: readonly string[];
234
+ readonly phase: 'waiting' | 'thinking' | 'responding' | 'tool' | 'awaiting_permission' | 'settling' | 'done' | 'error' | 'stopped' | 'disposed';
235
+ readonly replyText: string;
236
+ /** A factual recovery event, cleared when the next provider event arrives. */
237
+ readonly recovery?: 'connection' | 'provider';
238
+ readonly segments: readonly (({
239
+ readonly kind: 'text';
240
+ } & ProjectAgentPublicUpdate) | ProjectAgentToolActivity)[];
241
+ }
242
+ export interface ProjectAgentStopResponseRequest {
243
+ readonly workspaceId: string;
244
+ readonly turnId: string;
245
+ }
246
+ export type ProjectAgentStopResponseResult = {
247
+ readonly ok: true;
248
+ } | {
249
+ readonly ok: false;
250
+ readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'HOST_OFFLINE' | 'STALE_TURN' | 'INVALID_INPUT';
251
+ };
192
252
  export interface BotListSession {
193
253
  readonly status: WorkSessionStatus;
194
254
  readonly updatedAt?: string;
@@ -213,6 +273,9 @@ export declare function projectBotListItem(input: {
213
273
  readonly lastMessage?: BotListMessage | null;
214
274
  readonly sessions?: readonly BotListSession[];
215
275
  readonly approvals?: readonly BotListApproval[];
276
+ readonly attention?: readonly {
277
+ readonly id: string;
278
+ }[];
216
279
  readonly readCursor?: string | null;
217
280
  }): BotListItem;
218
281
  export declare function sortBotList(items: readonly BotListItem[]): BotListItem[];
package/dist/project.js CHANGED
@@ -22,7 +22,6 @@ export const BOT_AVATAR_COLORS = [
22
22
  '#55bac7',
23
23
  '#a8a59f',
24
24
  ];
25
- const NEEDS_YOU_STATUSES = new Set(['waiting_user', 'result_ready']);
26
25
  const RUNNING_STATUSES = new Set(['starting', 'running', 'verifying']);
27
26
  function fnv1a(text) {
28
27
  let hash = 0x811c9dc5;
@@ -51,9 +50,7 @@ function latestIso(values) {
51
50
  }
52
51
  export function projectBotListItem(input) {
53
52
  const sessions = input.sessions ?? [];
54
- const approvals = input.approvals ?? [];
55
- const openApprovals = approvals.filter((item) => item.state === 'open' || item.state === 'stale').length;
56
- const waitingSessions = sessions.filter((item) => NEEDS_YOU_STATUSES.has(item.status)).length;
53
+ const attention = new Set((input.attention ?? []).map(item => item.id));
57
54
  const running = sessions.filter((item) => RUNNING_STATUSES.has(item.status)).length;
58
55
  const lastMessage = input.lastMessage ?? null;
59
56
  const unread = lastMessage
@@ -72,7 +69,7 @@ export function projectBotListItem(input) {
72
69
  ...sessions.map((item) => item.updatedAt),
73
70
  ]),
74
71
  state: {
75
- needsYou: openApprovals + waitingSessions,
72
+ needsYou: attention.size,
76
73
  unread,
77
74
  running,
78
75
  },
@@ -0,0 +1,68 @@
1
+ import { type ResourceEditOperation, type ResourceEditReceipt } from './resource-edit.ts';
2
+ import { RESOURCE_FILE_REPLACE_CAPABILITY, RESOURCE_FILE_REPLACE_TOOL, type ResourceFileReplacePreview, type ResourceFileReplaceInput } from './resource-file-replace.ts';
3
+ import type { PermissionGrant } from './index.ts';
4
+ export declare const RESOURCE_EDIT_EXECUTION_BYTES = 32768;
5
+ export declare const RESOURCE_EDIT_POSTLUDE_BYTES = 16384;
6
+ export declare const RESOURCE_EDIT_EXECUTION_TOTAL_BYTES: number;
7
+ /** Stored facts have their own schema; they never contain the complete Tool Call arguments. */
8
+ export interface ResourceEditExecutionRecord {
9
+ readonly schemaVersion: 1;
10
+ readonly workspaceId: string;
11
+ readonly requestId: string;
12
+ readonly payloadHash: string;
13
+ readonly projectionId: string;
14
+ readonly sessionId: string;
15
+ readonly call: {
16
+ readonly toolCallId: string;
17
+ readonly capabilityId: typeof RESOURCE_FILE_REPLACE_CAPABILITY;
18
+ readonly toolName: typeof RESOURCE_FILE_REPLACE_TOOL;
19
+ readonly argumentsDigest: string;
20
+ readonly occurredAt: string;
21
+ readonly permissionCallId?: string;
22
+ };
23
+ readonly grant: Omit<PermissionGrant, 'scope'> & {
24
+ readonly scope?: typeof RESOURCE_FILE_REPLACE_CAPABILITY | null;
25
+ };
26
+ readonly result: {
27
+ readonly toolCallId: string;
28
+ readonly status: 'success' | 'failed' | 'denied' | 'cancelled';
29
+ readonly completedAt: string;
30
+ readonly observation?: ResourceFileReplacePreview;
31
+ readonly blockedReason?: string;
32
+ readonly evidence: {
33
+ readonly evidenceId: string;
34
+ readonly toolCallId: string;
35
+ readonly summary: string;
36
+ readonly locale: string;
37
+ readonly returnedToCloud: false;
38
+ readonly dataLevel: 'D2_sensitive';
39
+ readonly redactions: readonly string[];
40
+ readonly artifactRefs: readonly string[];
41
+ };
42
+ };
43
+ }
44
+ export interface ResourceEditHookFact {
45
+ readonly id?: string;
46
+ readonly event?: 'PreToolUse' | 'PostToolUse';
47
+ readonly decision: 'allow' | 'ask' | 'deny';
48
+ readonly reason?: string;
49
+ readonly outcome?: string;
50
+ readonly durationMs?: number;
51
+ readonly exitCode?: number | null;
52
+ }
53
+ export interface ResourceEditPostlude {
54
+ readonly schemaVersion: 1;
55
+ readonly requestId: string;
56
+ readonly payloadHash: string;
57
+ readonly completedAt: string;
58
+ readonly status: 'recorded' | 'unconfirmed';
59
+ readonly reason?: string;
60
+ readonly hookFinalDecision?: 'allow' | 'ask' | 'deny';
61
+ readonly hooks?: readonly ResourceEditHookFact[];
62
+ }
63
+ export declare function resourceFileReplaceArgumentPayload(raw: ResourceFileReplaceInput): string;
64
+ export declare function normalizeResourceEditExecutionRecord(raw: unknown): ResourceEditExecutionRecord | undefined;
65
+ export declare function resourceEditExecutionMatches(record: ResourceEditExecutionRecord, raw: ResourceEditOperation): boolean;
66
+ /** Caller must have obtained this record from the actual host execution index, never model text. */
67
+ export declare function resourceEditExecutionReceipt(record: ResourceEditExecutionRecord, operation: ResourceEditOperation): ResourceEditReceipt | undefined;
68
+ export declare function normalizeResourceEditPostlude(raw: unknown): ResourceEditPostlude | undefined;
@@ -0,0 +1,96 @@
1
+ import { normalizeResourceEditOperation, resourceEditToken, resourceEditDigest } from "./resource-edit.js";
2
+ import { normalizeResourceFileReplacePreview, normalizeResourceFileReplaceInput, RESOURCE_FILE_REPLACE_CAPABILITY, RESOURCE_FILE_REPLACE_PROVIDER, RESOURCE_FILE_REPLACE_TOOL } from "./resource-file-replace.js";
3
+ export const RESOURCE_EDIT_EXECUTION_BYTES = 32768;
4
+ export const RESOURCE_EDIT_POSTLUDE_BYTES = 16384;
5
+ export const RESOURCE_EDIT_EXECUTION_TOTAL_BYTES = 8 * 1024 * 1024;
6
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
7
+ const keys = (v, allowed) => Object.keys(v).every(key => allowed.includes(key));
8
+ const text = (v, max) => typeof v === 'string' && v.length > 0 && v.length <= max && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(v);
9
+ const timestamp = (v) => typeof v === 'string' && v.length <= 40 && Number.isFinite(Date.parse(v));
10
+ function bounded(raw, max) { try {
11
+ return new TextEncoder().encode(JSON.stringify(raw)).byteLength <= max;
12
+ }
13
+ catch {
14
+ return false;
15
+ } }
16
+ const strings = (v, maxItems, maxChars) => Array.isArray(v) && v.length <= maxItems && v.every(item => text(item, maxChars));
17
+ export function resourceFileReplaceArgumentPayload(raw) {
18
+ const input = normalizeResourceFileReplaceInput(raw);
19
+ if (!input)
20
+ throw TypeError('INVALID_RESOURCE_EDIT_ARGUMENTS');
21
+ return JSON.stringify(input);
22
+ }
23
+ export function normalizeResourceEditExecutionRecord(raw) {
24
+ if (!object(raw) || !bounded(raw, RESOURCE_EDIT_EXECUTION_BYTES) || !keys(raw, ['schemaVersion', 'workspaceId', 'requestId', 'payloadHash', 'projectionId', 'sessionId', 'call', 'grant', 'result'])
25
+ || raw.schemaVersion !== 1 || !resourceEditToken(raw.workspaceId) || !resourceEditToken(raw.requestId) || !resourceEditDigest(raw.payloadHash)
26
+ || raw.projectionId !== `resource-edit:${raw.requestId}` || !text(raw.sessionId, 256) || !object(raw.call) || !object(raw.grant) || !object(raw.result))
27
+ return;
28
+ const call = raw.call, grant = raw.grant, result = raw.result;
29
+ if (!keys(call, ['toolCallId', 'capabilityId', 'toolName', 'argumentsDigest', 'occurredAt', 'permissionCallId']) || call.toolCallId !== `resource-edit:${raw.requestId}`
30
+ || call.permissionCallId !== undefined && ![call.toolCallId, `chat-permission:${call.toolCallId}`].includes(call.permissionCallId)
31
+ || call.capabilityId !== RESOURCE_FILE_REPLACE_CAPABILITY || call.toolName !== RESOURCE_FILE_REPLACE_TOOL || !resourceEditDigest(call.argumentsDigest) || !timestamp(call.occurredAt)
32
+ || !keys(grant, ['grantId', 'toolCallId', 'granted', 'duration', 'scope', 'decidedAt', 'policyRevision']) || !resourceEditToken(grant.grantId) || grant.toolCallId !== call.toolCallId
33
+ || typeof grant.granted !== 'boolean' || !['once', 'task', 'session', 'scope', 'persistent', 'denied'].includes(grant.duration)
34
+ || grant.granted && (grant.duration === 'denied' || grant.scope !== call.capabilityId)
35
+ || !grant.granted && grant.scope !== undefined && grant.scope !== null && grant.scope !== call.capabilityId || !timestamp(grant.decidedAt)
36
+ || grant.policyRevision !== undefined && !text(grant.policyRevision, 512)
37
+ || !keys(result, ['toolCallId', 'status', 'completedAt', 'observation', 'blockedReason', 'evidence']) || result.toolCallId !== call.toolCallId || !timestamp(result.completedAt)
38
+ || !['success', 'failed', 'denied', 'cancelled'].includes(result.status) || !object(result.evidence))
39
+ return;
40
+ const observation = result.observation === undefined ? undefined : normalizeResourceFileReplacePreview(result.observation);
41
+ if (result.observation !== undefined && !observation || observation && (observation.requestId !== raw.requestId || observation.status !== result.status
42
+ || observation.permissionCallId !== undefined && (![call.toolCallId, `chat-permission:${call.toolCallId}`].includes(observation.permissionCallId)
43
+ || call.permissionCallId !== undefined && observation.permissionCallId !== call.permissionCallId)
44
+ || observation.outcome === 'applied' && !grant.granted)
45
+ || !observation && (!['denied', 'cancelled'].includes(result.status) || grant.granted || !text(result.blockedReason, 2048))
46
+ || observation && result.blockedReason !== undefined)
47
+ return;
48
+ const evidence = result.evidence;
49
+ if (!keys(evidence, ['evidenceId', 'toolCallId', 'summary', 'locale', 'returnedToCloud', 'dataLevel', 'redactions', 'artifactRefs']) || !resourceEditToken(evidence.evidenceId)
50
+ || evidence.toolCallId !== call.toolCallId || !text(evidence.summary, 4096) || !text(evidence.locale, 32) || evidence.returnedToCloud !== false || evidence.dataLevel !== 'D2_sensitive'
51
+ || !strings(evidence.redactions, 32, 256) || !strings(evidence.artifactRefs, 32, 2048))
52
+ return;
53
+ return { schemaVersion: 1, workspaceId: raw.workspaceId, requestId: raw.requestId, payloadHash: raw.payloadHash, projectionId: raw.projectionId, sessionId: raw.sessionId,
54
+ call: { toolCallId: call.toolCallId, capabilityId: RESOURCE_FILE_REPLACE_CAPABILITY, toolName: RESOURCE_FILE_REPLACE_TOOL, argumentsDigest: call.argumentsDigest, occurredAt: call.occurredAt,
55
+ ...(call.permissionCallId !== undefined || observation?.permissionCallId !== undefined ? { permissionCallId: (call.permissionCallId ?? observation?.permissionCallId) } : {}) },
56
+ grant: { grantId: grant.grantId, toolCallId: grant.toolCallId, granted: grant.granted, duration: grant.duration,
57
+ ...(grant.scope !== undefined ? { scope: grant.scope } : {}),
58
+ decidedAt: grant.decidedAt, ...(grant.policyRevision !== undefined ? { policyRevision: grant.policyRevision } : {}) },
59
+ result: { toolCallId: result.toolCallId, status: result.status, completedAt: result.completedAt,
60
+ ...(observation ? { observation } : { blockedReason: result.blockedReason }), evidence: { evidenceId: evidence.evidenceId, toolCallId: evidence.toolCallId,
61
+ summary: evidence.summary, locale: evidence.locale, returnedToCloud: false, dataLevel: 'D2_sensitive', redactions: [...evidence.redactions], artifactRefs: [...evidence.artifactRefs] } } };
62
+ }
63
+ export function resourceEditExecutionMatches(record, raw) {
64
+ const op = normalizeResourceEditOperation(raw), value = record.result.observation;
65
+ return !!op && op.providerId === RESOURCE_FILE_REPLACE_PROVIDER && op.requestId === record.requestId && op.target.recipient.workspaceId === record.workspaceId && op.payloadHash === record.payloadHash && record.sessionId === (op.target.reference.task?.sessionId ?? op.target.recipient.conversationId)
66
+ && (!value || value.path === op.target.reference.path && value.resourceId === op.target.base.resourceId && value.expectedVersion === op.target.base.contentVersion && value.proposedVersion === op.proposedVersion);
67
+ }
68
+ /** Caller must have obtained this record from the actual host execution index, never model text. */
69
+ export function resourceEditExecutionReceipt(record, operation) {
70
+ if (!resourceEditExecutionMatches(record, operation))
71
+ return;
72
+ const outcome = record.result.observation?.outcome ?? (record.result.status === 'cancelled' ? 'cancelled' : 'denied');
73
+ if (outcome === 'uncertain')
74
+ return;
75
+ return { outcome, toolCallId: record.call.toolCallId, evidenceRef: `tool-result://${record.call.toolCallId}`,
76
+ ...(record.result.observation?.observedVersion ? { observedVersion: record.result.observation.observedVersion } : {}) };
77
+ }
78
+ export function normalizeResourceEditPostlude(raw) {
79
+ if (!object(raw) || !bounded(raw, RESOURCE_EDIT_POSTLUDE_BYTES) || !keys(raw, ['schemaVersion', 'requestId', 'payloadHash', 'completedAt', 'status', 'reason', 'hookFinalDecision', 'hooks'])
80
+ || raw.schemaVersion !== 1 || !resourceEditToken(raw.requestId) || !resourceEditDigest(raw.payloadHash) || !timestamp(raw.completedAt) || !['recorded', 'unconfirmed'].includes(raw.status)
81
+ || raw.status === 'unconfirmed' && !text(raw.reason, 2048) || raw.reason !== undefined && !text(raw.reason, 2048) || raw.hookFinalDecision !== undefined && !['allow', 'ask', 'deny'].includes(raw.hookFinalDecision)
82
+ || raw.hooks !== undefined && (!Array.isArray(raw.hooks) || raw.hooks.length > 64))
83
+ return;
84
+ const hooks = [];
85
+ for (const item of (raw.hooks ?? [])) {
86
+ if (!object(item) || !keys(item, ['id', 'event', 'decision', 'reason', 'outcome', 'durationMs', 'exitCode']) || !['allow', 'ask', 'deny'].includes(item.decision)
87
+ || item.id !== undefined && !text(item.id, 512) || item.event !== undefined && !['PreToolUse', 'PostToolUse'].includes(item.event)
88
+ || item.reason !== undefined && !text(item.reason, 2048) || item.outcome !== undefined && !text(item.outcome, 128)
89
+ || item.durationMs !== undefined && (typeof item.durationMs !== 'number' || !Number.isFinite(item.durationMs) || item.durationMs < 0)
90
+ || item.exitCode !== undefined && item.exitCode !== null && !Number.isSafeInteger(item.exitCode))
91
+ return;
92
+ hooks.push({ ...item });
93
+ }
94
+ return { schemaVersion: 1, requestId: raw.requestId, payloadHash: raw.payloadHash, completedAt: raw.completedAt, status: raw.status,
95
+ ...(raw.reason !== undefined ? { reason: raw.reason } : {}), ...(raw.hookFinalDecision !== undefined ? { hookFinalDecision: raw.hookFinalDecision } : {}), ...(raw.hooks !== undefined ? { hooks } : {}) };
96
+ }
@@ -0,0 +1,237 @@
1
+ import type { BotDocumentReference } from './document-reference.ts';
2
+ import type { ResourceFeedbackRecipient, ResourceFeedbackPreparationIdentity } from './resource-feedback.ts';
3
+ /** Recoverable intent only. These records never grant filesystem access or prove execution. */
4
+ export interface ResourceEditTarget {
5
+ readonly recipient: ResourceFeedbackRecipient;
6
+ readonly reference: BotDocumentReference;
7
+ readonly base: {
8
+ readonly resourceId: string;
9
+ readonly contentVersion: string;
10
+ };
11
+ }
12
+ export interface ResourceTextDraft {
13
+ readonly id: string;
14
+ readonly target: ResourceEditTarget;
15
+ readonly baseText: string;
16
+ readonly text: string;
17
+ readonly revision: number;
18
+ readonly createdAt: string;
19
+ readonly updatedAt: string;
20
+ }
21
+ /** Host validates the real sender separately. A token cannot substitute for PermissionGrant. */
22
+ export interface ResourceEditWriter extends ResourceFeedbackPreparationIdentity {
23
+ readonly token: string;
24
+ readonly lease: number;
25
+ }
26
+ export interface ResourceEditReceipt {
27
+ readonly outcome: 'applied' | 'conflict' | 'denied' | 'cancelled' | 'failed';
28
+ readonly toolCallId?: string;
29
+ readonly evidenceRef?: string;
30
+ readonly observedVersion?: string;
31
+ }
32
+ export interface ResourceEditOperation {
33
+ readonly requestId: string;
34
+ readonly draftId: string;
35
+ readonly draftRevision: number;
36
+ readonly target: ResourceEditTarget;
37
+ readonly providerId: string;
38
+ readonly proposedVersion: string;
39
+ readonly payloadHash: string;
40
+ readonly createdAt: string;
41
+ readonly updatedAt: string;
42
+ readonly phase: 'prepared' | 'running' | 'uncertain' | 'settled';
43
+ readonly hostEpoch?: string;
44
+ readonly receipt?: ResourceEditReceipt;
45
+ }
46
+ export declare const RESOURCE_TEXT_DRAFT_LIMIT = 16;
47
+ export declare const RESOURCE_EDIT_OPERATION_LIMIT = 64;
48
+ export declare const RESOURCE_EDIT_TEXT_BYTES: number;
49
+ export declare const resourceEditToken: (v: unknown) => v is string;
50
+ export declare const resourceEditDigest: (v: unknown) => v is string;
51
+ export declare function validResourceEditText(v: unknown): v is string;
52
+ export declare function normalizeResourceEditTarget(raw: unknown): ResourceEditTarget | undefined;
53
+ export declare function normalizeResourceTextDraft(raw: unknown): ResourceTextDraft | undefined;
54
+ export declare function normalizeResourceEditWriter(raw: unknown): ResourceEditWriter | undefined;
55
+ export declare function normalizeResourceEditReceipt(raw: unknown): ResourceEditReceipt | undefined;
56
+ export declare function normalizeResourceEditOperation(raw: unknown): ResourceEditOperation | undefined;
57
+ /** Retained text is a version, not current filesystem authority or task acceptance. */
58
+ export interface ResourceTextSnapshot {
59
+ readonly id: string;
60
+ readonly target: ResourceEditTarget;
61
+ readonly version: string;
62
+ readonly createdAt: string;
63
+ readonly purpose: 'before' | 'after' | 'delivery';
64
+ readonly availability: 'retained' | 'cleaned';
65
+ readonly evidenceRef: string;
66
+ readonly toolCallId?: string;
67
+ readonly operationId?: string;
68
+ readonly artifactRef?: string;
69
+ }
70
+ export declare function normalizeResourceTextSnapshot(raw: unknown): ResourceTextSnapshot | undefined;
71
+ export type ResourceEditSource = {
72
+ readonly kind: 'document';
73
+ readonly reference: BotDocumentReference;
74
+ readonly observed: ResourceEditTarget['base'];
75
+ } | {
76
+ readonly kind: 'native';
77
+ readonly identity: import('./resource-window.ts').ResourceWindowIdentity;
78
+ readonly path?: string;
79
+ readonly observed: ResourceEditTarget['base'];
80
+ };
81
+ export interface ResourceEditViewHandle {
82
+ readonly viewId: string;
83
+ readonly windowId: string;
84
+ readonly generation: number;
85
+ readonly draftId: string;
86
+ }
87
+ export interface ResourceEditView {
88
+ readonly handle: ResourceEditViewHandle;
89
+ readonly draft: ResourceTextDraft;
90
+ }
91
+ export type ResourceEditResult<T extends object = Record<never, never>> = ({
92
+ readonly ok: true;
93
+ } & T) | {
94
+ readonly ok: false;
95
+ readonly code: string;
96
+ };
97
+ export interface ResourceEditScope {
98
+ readonly workspaceId: string;
99
+ readonly handle?: ResourceEditViewHandle;
100
+ }
101
+ export interface ResourceEditDraftInfo extends Omit<ResourceTextDraft, 'baseText' | 'text'> {
102
+ readonly hasChanges: boolean;
103
+ }
104
+ export interface ResourceEditNotice {
105
+ readonly workspaceId: string;
106
+ readonly draftId?: string;
107
+ readonly kind: 'writer' | 'saved' | 'discarded' | 'history' | 'operation';
108
+ readonly requestId?: string;
109
+ readonly writerViewId?: string;
110
+ readonly revision?: number;
111
+ }
112
+ export interface ResourceEditSaveReceipt {
113
+ readonly draftId: string;
114
+ readonly revision: number;
115
+ readonly updatedAt: string;
116
+ readonly textVersion: string;
117
+ }
118
+ export interface ResourceEditOperationRequest {
119
+ readonly handle: ResourceEditViewHandle;
120
+ readonly requestId: string;
121
+ }
122
+ export interface ResourceEditPermissionChallenge {
123
+ readonly requestId: string;
124
+ readonly challengeId: string;
125
+ readonly argsDigest: string;
126
+ readonly deadlineAt: string;
127
+ readonly path: string;
128
+ readonly expectedVersion: string;
129
+ readonly proposedVersion: string;
130
+ readonly reason: string;
131
+ readonly confirmation?: string;
132
+ }
133
+ export interface ResourceEditOperationStatus {
134
+ readonly operation: ResourceEditOperation;
135
+ readonly live: boolean;
136
+ readonly hostOwnedHere?: boolean;
137
+ readonly hasActualResult: boolean;
138
+ readonly governance: 'pending' | 'recorded' | 'unconfirmed' | 'unavailable';
139
+ readonly permission: ResourceEditPermissionChallenge | null;
140
+ readonly permissionElsewhere?: boolean;
141
+ readonly observation?: 'matches_proposed' | 'matches_base' | 'changed' | 'unavailable';
142
+ }
143
+ export interface ResourceEditsApi {
144
+ readonly onChanged: (listener: (notice: ResourceEditNotice) => void) => () => void;
145
+ readonly open: (request: {
146
+ readonly requestId: string;
147
+ readonly source: ResourceEditSource;
148
+ }) => Promise<ResourceEditResult<ResourceEditView>>;
149
+ readonly resume: (request: {
150
+ readonly requestId: string;
151
+ readonly workspaceId: string;
152
+ readonly draftId: string;
153
+ readonly source?: ResourceEditSource;
154
+ }) => Promise<ResourceEditResult<ResourceEditView>>;
155
+ readonly cancelOpen: (requestId: string) => Promise<ResourceEditResult>;
156
+ readonly read: (handle: ResourceEditViewHandle) => Promise<ResourceEditResult<ResourceEditView>>;
157
+ readonly acquire: (request: {
158
+ readonly handle: ResourceEditViewHandle;
159
+ readonly takeover?: boolean;
160
+ }) => Promise<ResourceEditResult<ResourceEditView & {
161
+ readonly writer: ResourceEditWriter;
162
+ }>>;
163
+ readonly save: (request: {
164
+ readonly handle: ResourceEditViewHandle;
165
+ readonly writer: ResourceEditWriter;
166
+ readonly revision: number;
167
+ readonly text: string;
168
+ }) => Promise<ResourceEditResult<{
169
+ readonly saved: ResourceEditSaveReceipt;
170
+ }>>;
171
+ readonly discard: (request: {
172
+ readonly handle: ResourceEditViewHandle;
173
+ readonly writer: ResourceEditWriter;
174
+ readonly revision: number;
175
+ }) => Promise<ResourceEditResult>;
176
+ readonly close: (handle: ResourceEditViewHandle) => Promise<ResourceEditResult>;
177
+ readonly list: (request: ResourceEditScope & {
178
+ readonly cursor?: string;
179
+ readonly limit?: number;
180
+ }) => Promise<ResourceEditResult<{
181
+ readonly drafts: readonly ResourceEditDraftInfo[];
182
+ readonly operations: readonly ResourceEditOperation[];
183
+ readonly nextCursor: string | null;
184
+ readonly staleCount: number;
185
+ }>>;
186
+ readonly history: (request: ResourceEditScope & {
187
+ readonly cursor?: string;
188
+ readonly limit?: number;
189
+ }) => Promise<ResourceEditResult<{
190
+ readonly items: readonly ResourceTextSnapshot[];
191
+ readonly nextCursor: string | null;
192
+ readonly unavailableCount: number;
193
+ }>>;
194
+ readonly readSnapshot: (request: ResourceEditScope & {
195
+ readonly id: string;
196
+ }) => Promise<ResourceEditResult<{
197
+ readonly snapshot: ResourceTextSnapshot;
198
+ readonly content: string;
199
+ }>>;
200
+ readonly cleanup: (request: ResourceEditScope & {
201
+ readonly requestIds: readonly string[];
202
+ }) => Promise<ResourceEditResult<{
203
+ readonly removedBytes: number;
204
+ }>>;
205
+ readonly archive: (request: ResourceEditScope & {
206
+ readonly requestId: string;
207
+ }) => Promise<ResourceEditResult>;
208
+ readonly clearDelivery: (request: ResourceEditScope & {
209
+ readonly id: string;
210
+ }) => Promise<ResourceEditResult<{
211
+ readonly removedBytes: number;
212
+ }>>;
213
+ readonly submit: (request: ResourceEditOperationRequest & {
214
+ readonly writer: ResourceEditWriter;
215
+ readonly revision: number;
216
+ }) => Promise<ResourceEditResult<ResourceEditOperationStatus>>;
217
+ readonly continueSubmission: (request: ResourceEditOperationRequest) => Promise<ResourceEditResult<ResourceEditOperationStatus>>;
218
+ readonly operationStatus: (request: ResourceEditOperationRequest) => Promise<ResourceEditResult<ResourceEditOperationStatus>>;
219
+ readonly reconcileSubmission: (request: ResourceEditOperationRequest) => Promise<ResourceEditResult<ResourceEditOperationStatus>>;
220
+ readonly cancelSubmission: (request: ResourceEditOperationRequest) => Promise<ResourceEditResult<ResourceEditOperationStatus>>;
221
+ readonly decideSubmissionPermission: (request: ResourceEditOperationRequest & {
222
+ readonly challengeId: string;
223
+ readonly argsDigest: string;
224
+ readonly allow: boolean;
225
+ }) => Promise<ResourceEditResult>;
226
+ readonly readExecution: (request: ResourceEditOperationRequest) => Promise<ResourceEditResult<{
227
+ readonly record: import('./resource-edit-execution.ts').ResourceEditExecutionRecord;
228
+ readonly postlude: import('./resource-edit-execution.ts').ResourceEditPostlude | null;
229
+ }>>;
230
+ readonly readSubmission: (request: ResourceEditOperationRequest) => Promise<ResourceEditResult<{
231
+ readonly operation: ResourceEditOperation;
232
+ readonly baseText: string;
233
+ readonly text: string;
234
+ }>>;
235
+ }
236
+ export declare function normalizeResourceEditSource(raw: unknown): ResourceEditSource | undefined;
237
+ export declare function normalizeResourceEditHandle(raw: unknown): ResourceEditViewHandle | undefined;
@@ -0,0 +1,134 @@
1
+ import { normalizeResourceWindowRequest } from "./resource-window.js";
2
+ export const RESOURCE_TEXT_DRAFT_LIMIT = 16;
3
+ export const RESOURCE_EDIT_OPERATION_LIMIT = 64;
4
+ export const RESOURCE_EDIT_TEXT_BYTES = 1024 * 1024;
5
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
6
+ const keys = (v, allowed) => Object.keys(v).every(k => allowed.includes(k));
7
+ export const resourceEditToken = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(v) && !v.includes('..');
8
+ export const resourceEditDigest = (v) => typeof v === 'string' && /^sha256:[a-f0-9]{64}$/.test(v);
9
+ const integer = (v) => Number.isSafeInteger(v) && Number(v) >= 0;
10
+ const timestamp = (v) => typeof v === 'string' && v.length <= 40 && Number.isFinite(Date.parse(v));
11
+ const metadataText = (v) => typeof v === 'string' && !!v.trim() && v.length <= 2048 && !/[\u0000-\u001f]/.test(v);
12
+ export function validResourceEditText(v) {
13
+ if (typeof v !== 'string' || v.length > RESOURCE_EDIT_TEXT_BYTES || v.includes('\u0000'))
14
+ return false;
15
+ for (let i = 0; i < v.length; i++) {
16
+ const n = v.charCodeAt(i);
17
+ if (n >= 0xd800 && n <= 0xdbff) {
18
+ const next = v.charCodeAt(++i);
19
+ if (!(next >= 0xdc00 && next <= 0xdfff))
20
+ return false;
21
+ }
22
+ else if (n >= 0xdc00 && n <= 0xdfff)
23
+ return false;
24
+ }
25
+ return new TextEncoder().encode(v).byteLength <= RESOURCE_EDIT_TEXT_BYTES;
26
+ }
27
+ export function normalizeResourceEditTarget(raw) {
28
+ if (!object(raw) || !keys(raw, ['recipient', 'reference', 'base']) || !object(raw.recipient)
29
+ || !keys(raw.recipient, ['workspaceId', 'conversationId']) || !resourceEditToken(raw.recipient.workspaceId) || !resourceEditToken(raw.recipient.conversationId)
30
+ || !object(raw.base) || !keys(raw.base, ['resourceId', 'contentVersion']) || !resourceEditDigest(raw.base.resourceId) || !resourceEditDigest(raw.base.contentVersion))
31
+ return;
32
+ const normalized = normalizeResourceWindowRequest({ resource: { kind: 'document', mode: 'source', reference: raw.reference } });
33
+ const reference = normalized?.resource.reference;
34
+ if (!reference || reference.revision || reference.kind === 'directory' || reference.relativeTo !== undefined
35
+ || reference.workspaceId !== raw.recipient.workspaceId || !/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(reference.path))
36
+ return;
37
+ if (reference.expectedObservation && (reference.expectedObservation.resourceId !== raw.base.resourceId
38
+ || reference.expectedObservation.contentVersion !== undefined && reference.expectedObservation.contentVersion !== raw.base.contentVersion))
39
+ return;
40
+ return { recipient: { workspaceId: raw.recipient.workspaceId, conversationId: raw.recipient.conversationId },
41
+ reference: { ...reference, kind: 'file', expectedObservation: { resourceId: raw.base.resourceId, contentVersion: raw.base.contentVersion } },
42
+ base: { resourceId: raw.base.resourceId, contentVersion: raw.base.contentVersion } };
43
+ }
44
+ export function normalizeResourceTextDraft(raw) {
45
+ if (!object(raw) || !keys(raw, ['id', 'target', 'baseText', 'text', 'revision', 'createdAt', 'updatedAt']) || !resourceEditToken(raw.id)
46
+ || !validResourceEditText(raw.baseText) || !validResourceEditText(raw.text) || !integer(raw.revision) || !timestamp(raw.createdAt) || !timestamp(raw.updatedAt))
47
+ return;
48
+ const target = normalizeResourceEditTarget(raw.target);
49
+ if (!target)
50
+ return;
51
+ return { id: raw.id, target, baseText: raw.baseText, text: raw.text, revision: raw.revision,
52
+ createdAt: new Date(raw.createdAt).toISOString(), updatedAt: new Date(raw.updatedAt).toISOString() };
53
+ }
54
+ export function normalizeResourceEditWriter(raw) {
55
+ if (!object(raw) || !keys(raw, ['viewId', 'windowId', 'generation', 'token', 'lease']) || !resourceEditToken(raw.viewId) || !resourceEditToken(raw.windowId)
56
+ || !resourceEditToken(raw.token) || !integer(raw.lease) || raw.lease < 1
57
+ || !(resourceEditToken(raw.generation) || integer(raw.generation) && raw.generation > 0))
58
+ return;
59
+ return { viewId: raw.viewId, windowId: raw.windowId, generation: raw.generation, token: raw.token, lease: raw.lease };
60
+ }
61
+ export function normalizeResourceEditReceipt(raw) {
62
+ if (!object(raw) || !keys(raw, ['outcome', 'toolCallId', 'evidenceRef', 'observedVersion'])
63
+ || typeof raw.outcome !== 'string' || !['applied', 'conflict', 'denied', 'cancelled', 'failed'].includes(raw.outcome)
64
+ || raw.toolCallId !== undefined && !metadataText(raw.toolCallId) || raw.evidenceRef !== undefined && !metadataText(raw.evidenceRef)
65
+ || (raw.toolCallId === undefined) !== (raw.evidenceRef === undefined)
66
+ || raw.observedVersion !== undefined && !resourceEditDigest(raw.observedVersion)
67
+ || raw.outcome === 'applied' && (raw.toolCallId === undefined || raw.evidenceRef === undefined || raw.observedVersion === undefined))
68
+ return;
69
+ return { outcome: raw.outcome, ...(raw.toolCallId !== undefined ? { toolCallId: raw.toolCallId, evidenceRef: raw.evidenceRef } : {}),
70
+ ...(raw.observedVersion !== undefined ? { observedVersion: raw.observedVersion } : {}) };
71
+ }
72
+ export function normalizeResourceEditOperation(raw) {
73
+ if (!object(raw) || !keys(raw, ['requestId', 'draftId', 'draftRevision', 'target', 'providerId', 'proposedVersion', 'payloadHash', 'createdAt', 'updatedAt', 'phase', 'hostEpoch', 'receipt'])
74
+ || !resourceEditToken(raw.requestId) || !resourceEditToken(raw.draftId) || !integer(raw.draftRevision) || !resourceEditToken(raw.providerId)
75
+ || !resourceEditDigest(raw.proposedVersion) || !resourceEditDigest(raw.payloadHash) || !timestamp(raw.createdAt) || !timestamp(raw.updatedAt)
76
+ || typeof raw.phase !== 'string' || !['prepared', 'running', 'uncertain', 'settled'].includes(raw.phase)
77
+ || raw.hostEpoch !== undefined && !resourceEditToken(raw.hostEpoch))
78
+ return;
79
+ const target = normalizeResourceEditTarget(raw.target), receipt = raw.receipt !== undefined ? normalizeResourceEditReceipt(raw.receipt) : undefined;
80
+ if (!target || raw.receipt !== undefined && !receipt || (raw.phase === 'running' || raw.phase === 'uncertain') && raw.hostEpoch === undefined
81
+ || raw.phase === 'prepared' && raw.hostEpoch !== undefined || (raw.phase === 'settled') !== !!receipt
82
+ || receipt?.outcome === 'applied' && receipt.observedVersion !== raw.proposedVersion)
83
+ return;
84
+ return { requestId: raw.requestId, draftId: raw.draftId, draftRevision: raw.draftRevision, target, providerId: raw.providerId,
85
+ proposedVersion: raw.proposedVersion, payloadHash: raw.payloadHash, createdAt: new Date(raw.createdAt).toISOString(), updatedAt: new Date(raw.updatedAt).toISOString(),
86
+ phase: raw.phase, ...(raw.hostEpoch !== undefined ? { hostEpoch: raw.hostEpoch } : {}), ...(receipt ? { receipt } : {}) };
87
+ }
88
+ export function normalizeResourceTextSnapshot(raw) {
89
+ if (!object(raw) || !keys(raw, ['id', 'target', 'version', 'createdAt', 'purpose', 'availability', 'evidenceRef', 'toolCallId', 'operationId', 'artifactRef'])
90
+ || !resourceEditToken(raw.id) || !resourceEditDigest(raw.version) || !timestamp(raw.createdAt) || !metadataText(raw.evidenceRef)
91
+ || !['before', 'after', 'delivery'].includes(raw.purpose) || !['retained', 'cleaned'].includes(raw.availability)
92
+ || raw.toolCallId !== undefined && !metadataText(raw.toolCallId) || raw.operationId !== undefined && !resourceEditToken(raw.operationId)
93
+ || raw.artifactRef !== undefined && !metadataText(raw.artifactRef))
94
+ return;
95
+ const target = normalizeResourceEditTarget(raw.target);
96
+ if (!target)
97
+ return;
98
+ if (raw.purpose === 'delivery' ? !metadataText(raw.artifactRef) || raw.operationId !== undefined || raw.version !== target.base.contentVersion
99
+ : !resourceEditToken(raw.operationId) || !metadataText(raw.toolCallId) || raw.artifactRef !== undefined || raw.purpose === 'before' && raw.version !== target.base.contentVersion)
100
+ return;
101
+ return { id: raw.id, target, version: raw.version, createdAt: new Date(raw.createdAt).toISOString(), purpose: raw.purpose,
102
+ availability: raw.availability, evidenceRef: raw.evidenceRef,
103
+ ...(raw.toolCallId !== undefined ? { toolCallId: raw.toolCallId } : {}), ...(raw.operationId !== undefined ? { operationId: raw.operationId } : {}),
104
+ ...(raw.artifactRef !== undefined ? { artifactRef: raw.artifactRef } : {}) };
105
+ }
106
+ export function normalizeResourceEditSource(raw) {
107
+ if (!object(raw) || !object(raw.observed) || !keys(raw.observed, ['resourceId', 'contentVersion'])
108
+ || !resourceEditDigest(raw.observed.resourceId) || !resourceEditDigest(raw.observed.contentVersion))
109
+ return;
110
+ const observed = { resourceId: raw.observed.resourceId, contentVersion: raw.observed.contentVersion };
111
+ if (raw.kind === 'document') {
112
+ if (!keys(raw, ['kind', 'reference', 'observed']))
113
+ return;
114
+ const normalized = normalizeResourceWindowRequest({ resource: { kind: 'document', mode: 'source', reference: raw.reference } });
115
+ const reference = normalized?.resource.reference;
116
+ if (!reference || reference.kind === 'directory' || reference.revision || reference.expectedObservation
117
+ && (reference.expectedObservation.resourceId !== observed.resourceId || reference.expectedObservation.contentVersion !== undefined && reference.expectedObservation.contentVersion !== observed.contentVersion))
118
+ return;
119
+ return { kind: 'document', reference: { ...reference, kind: 'file', expectedObservation: observed }, observed };
120
+ }
121
+ if (raw.kind !== 'native' || !keys(raw, ['kind', 'identity', 'path', 'observed']) || !object(raw.identity)
122
+ || !keys(raw.identity, ['viewId', 'windowId', 'generation']) || !resourceEditToken(raw.identity.viewId) || !resourceEditToken(raw.identity.windowId)
123
+ || !integer(raw.identity.generation) || raw.identity.generation < 1
124
+ || raw.path !== undefined && (typeof raw.path !== 'string' || raw.path.length > 8192 || /[\u0000-\u001f]/.test(raw.path) || !/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(raw.path)))
125
+ return;
126
+ return { kind: 'native', identity: { viewId: raw.identity.viewId, windowId: raw.identity.windowId, generation: raw.identity.generation }, observed,
127
+ ...(typeof raw.path === 'string' ? { path: raw.path } : {}) };
128
+ }
129
+ export function normalizeResourceEditHandle(raw) {
130
+ if (!object(raw) || !keys(raw, ['viewId', 'windowId', 'generation', 'draftId']) || !resourceEditToken(raw.viewId) || !resourceEditToken(raw.windowId) || !resourceEditToken(raw.draftId)
131
+ || !integer(raw.generation) || raw.generation < 1)
132
+ return;
133
+ return { viewId: raw.viewId, windowId: raw.windowId, generation: raw.generation, draftId: raw.draftId };
134
+ }