@peer-agent/protocol 0.1.0-rc.41 → 0.1.0-rc.42
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.
- package/dist/compaction-history-selection.d.ts +15 -0
- package/dist/compaction-history-selection.js +30 -0
- package/dist/compaction.d.ts +5 -0
- package/dist/compaction.js +6 -0
- package/dist/context-accounting.d.ts +3 -0
- package/dist/conversation-execution.d.ts +58 -0
- package/dist/conversation-execution.js +183 -0
- package/dist/delegation.d.ts +8 -0
- package/dist/delegation.js +1 -0
- package/dist/hook-observation.d.ts +2 -0
- package/dist/hook-observation.js +19 -0
- package/dist/index.d.ts +33 -19
- package/dist/index.js +4 -0
- package/dist/input-prediction.d.ts +2 -2
- package/dist/input-prediction.js +2 -2
- package/dist/local-read.d.ts +9 -0
- package/dist/local-read.js +1 -0
- package/dist/native-process.d.ts +21 -0
- package/dist/native-process.js +51 -0
- package/dist/project-input-recovery.d.ts +9 -1
- package/dist/project.d.ts +50 -0
- package/dist/project.js +113 -0
- package/dist/runtime-session-facts.js +4 -2
- package/dist/session-control.d.ts +12 -0
- package/dist/task-overview.d.ts +2 -1
- package/dist/task-overview.js +4 -1
- package/dist/usage-accounting.d.ts +29 -0
- package/dist/work-coordination.d.ts +23 -0
- package/dist/work-hook.d.ts +3 -0
- package/dist/work-hook.js +76 -0
- package/package.json +1 -1
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Source references only; this object never proves a capability result. */
|
|
2
|
+
export interface CompactionHistorySelection {
|
|
3
|
+
readonly version: 1;
|
|
4
|
+
readonly compactionEpoch: number;
|
|
5
|
+
readonly retainedMessageIds: readonly string[];
|
|
6
|
+
}
|
|
7
|
+
/** Checked against the language-neutral resource by native CLI conformance. */
|
|
8
|
+
export declare const COMPACTION_HISTORY_SELECTION_LIMITS: Readonly<{
|
|
9
|
+
version: 1;
|
|
10
|
+
projectorVersion: 3;
|
|
11
|
+
maxRetained: 4096;
|
|
12
|
+
maxIdBytes: 200;
|
|
13
|
+
maxSelectionBytes: 65536;
|
|
14
|
+
}>;
|
|
15
|
+
export declare function normalizeCompactionHistorySelection(value: unknown): CompactionHistorySelection | null;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Checked against the language-neutral resource by native CLI conformance. */
|
|
2
|
+
export const COMPACTION_HISTORY_SELECTION_LIMITS = Object.freeze({
|
|
3
|
+
version: 1, projectorVersion: 3, maxRetained: 4096, maxIdBytes: 200, maxSelectionBytes: 65536,
|
|
4
|
+
});
|
|
5
|
+
export function normalizeCompactionHistorySelection(value) {
|
|
6
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
7
|
+
return null;
|
|
8
|
+
const row = value;
|
|
9
|
+
if (Object.keys(row).some(k => !['version', 'compactionEpoch', 'retainedMessageIds'].includes(k))
|
|
10
|
+
|| row.version !== 1 || !Number.isSafeInteger(row.compactionEpoch) || Number(row.compactionEpoch) <= 0
|
|
11
|
+
|| !Array.isArray(row.retainedMessageIds) || row.retainedMessageIds.length > COMPACTION_HISTORY_SELECTION_LIMITS.maxRetained)
|
|
12
|
+
return null;
|
|
13
|
+
const seen = new Set();
|
|
14
|
+
const encoder = new TextEncoder();
|
|
15
|
+
let bytes = 0;
|
|
16
|
+
for (const id of row.retainedMessageIds) {
|
|
17
|
+
if (typeof id !== 'string' || !id || seen.has(id))
|
|
18
|
+
return null;
|
|
19
|
+
if ([...id].some(c => { const point = c.codePointAt(0); return point >= 0xD800 && point <= 0xDFFF; }))
|
|
20
|
+
return null;
|
|
21
|
+
const size = encoder.encode(id).length;
|
|
22
|
+
if (size > COMPACTION_HISTORY_SELECTION_LIMITS.maxIdBytes)
|
|
23
|
+
return null;
|
|
24
|
+
bytes += size;
|
|
25
|
+
seen.add(id);
|
|
26
|
+
}
|
|
27
|
+
if (bytes > COMPACTION_HISTORY_SELECTION_LIMITS.maxSelectionBytes)
|
|
28
|
+
return null;
|
|
29
|
+
return { version: 1, compactionEpoch: Number(row.compactionEpoch), retainedMessageIds: [...seen] };
|
|
30
|
+
}
|
package/dist/compaction.d.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
import { type CompactionHistorySelection } from './compaction-history-selection.ts';
|
|
2
|
+
export { normalizeCompactionHistorySelection, COMPACTION_HISTORY_SELECTION_LIMITS } from './compaction-history-selection.ts';
|
|
3
|
+
export type { CompactionHistorySelection } from './compaction-history-selection.ts';
|
|
1
4
|
/** 压缩摘要的产生方式,与 runtime-core CompactionMethod 保持同枚举。 */
|
|
2
5
|
export type CompactionMarkerMethod = 'llm' | 'structured' | 'structural' | 'fallback_drop';
|
|
3
6
|
/** 持久化在 handoff 消息 `_compaction` 字段上的共享 marker 形状。 */
|
|
4
7
|
export interface ConversationCompactionMarker {
|
|
8
|
+
readonly historySelection?: CompactionHistorySelection;
|
|
5
9
|
readonly method: CompactionMarkerMethod;
|
|
6
10
|
/** LLM 摘要失败降级原因(仅降级时存在)。 */
|
|
7
11
|
readonly fallbackReason?: string;
|
|
@@ -35,6 +39,7 @@ export interface ConversationCompactionMarker {
|
|
|
35
39
|
* 数值一律钳制为非负整数;method 非法时回退 'structured';可选降级字段仅在非空时出现。
|
|
36
40
|
*/
|
|
37
41
|
export declare function buildCompactionMarker(input: {
|
|
42
|
+
readonly historySelection?: CompactionHistorySelection | null;
|
|
38
43
|
readonly method?: unknown;
|
|
39
44
|
readonly fallbackReason?: string | null;
|
|
40
45
|
readonly fallbackDetail?: string | null;
|
package/dist/compaction.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
// `_compaction` marker 是 Desktop 与 CLI/TUI 共享会话事实面的一部分:
|
|
4
4
|
// 任一端压缩后,另一端必须能按同一形状恢复 active provider history 分界与连续性摘要。
|
|
5
5
|
// 两端持久化必须经 buildCompactionMarker() 产出,不得手写字面量,防止字段漂移。
|
|
6
|
+
import { normalizeCompactionHistorySelection } from "./compaction-history-selection.js";
|
|
7
|
+
export { normalizeCompactionHistorySelection, COMPACTION_HISTORY_SELECTION_LIMITS } from "./compaction-history-selection.js";
|
|
6
8
|
function nonNegativeInt(value) {
|
|
7
9
|
const parsed = Number(value);
|
|
8
10
|
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;
|
|
@@ -17,6 +19,9 @@ function normalizeMethod(value) {
|
|
|
17
19
|
* 数值一律钳制为非负整数;method 非法时回退 'structured';可选降级字段仅在非空时出现。
|
|
18
20
|
*/
|
|
19
21
|
export function buildCompactionMarker(input) {
|
|
22
|
+
const selection = input.historySelection == null ? null : normalizeCompactionHistorySelection(input.historySelection);
|
|
23
|
+
if (input.historySelection != null && (!selection || typeof input.summary !== 'string' || !input.summary.trim()))
|
|
24
|
+
throw new Error('compaction_history_selection_invalid');
|
|
20
25
|
const fallbackReason = typeof input.fallbackReason === 'string' && input.fallbackReason.trim()
|
|
21
26
|
? input.fallbackReason
|
|
22
27
|
: undefined;
|
|
@@ -24,6 +29,7 @@ export function buildCompactionMarker(input) {
|
|
|
24
29
|
? input.fallbackDetail
|
|
25
30
|
: undefined;
|
|
26
31
|
return {
|
|
32
|
+
...(selection ? { historySelection: selection } : {}),
|
|
27
33
|
method: normalizeMethod(input.method),
|
|
28
34
|
...(fallbackReason ? { fallbackReason } : {}),
|
|
29
35
|
...(fallbackDetail ? { fallbackDetail } : {}),
|
|
@@ -82,6 +82,9 @@ export declare function normalizeContextUsageBreakdown(value: unknown): ContextU
|
|
|
82
82
|
*/
|
|
83
83
|
export interface ContextAccountingSnapshot {
|
|
84
84
|
readonly version: 1;
|
|
85
|
+
/** Durable occupancy binding; required for append-only historySelection. */
|
|
86
|
+
readonly projectorVersion?: 3;
|
|
87
|
+
readonly compactionBoundaryId?: string | null;
|
|
85
88
|
readonly conversationId: string;
|
|
86
89
|
readonly contentRevision: number;
|
|
87
90
|
readonly modelKey: string;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Ordinary execution facts in the original Conversation index. Shape is never
|
|
2
|
+
* permission, process-death proof, or authority to replay a pending dispatch. */
|
|
3
|
+
import { type SessionControlOperation } from './session-control.ts';
|
|
4
|
+
type Recorder = NonNullable<SessionControlOperation['recorder']>;
|
|
5
|
+
export interface ConversationExecutionIdentity {
|
|
6
|
+
readonly kind: 'conversation';
|
|
7
|
+
readonly conversationId: string;
|
|
8
|
+
readonly streamId: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ConversationExecution {
|
|
11
|
+
readonly schemaVersion: 1;
|
|
12
|
+
readonly identity: ConversationExecutionIdentity;
|
|
13
|
+
readonly engine: 'peer-native' | 'peer-ts';
|
|
14
|
+
readonly owner: Recorder;
|
|
15
|
+
readonly revision: number;
|
|
16
|
+
readonly phase: 'active' | 'stopping' | 'stopped' | 'recovery_required';
|
|
17
|
+
readonly pendingTools: readonly {
|
|
18
|
+
readonly toolCallId: string;
|
|
19
|
+
readonly dispatchId: string;
|
|
20
|
+
readonly messageId: string;
|
|
21
|
+
readonly capabilityId: string;
|
|
22
|
+
readonly argsDigest: string;
|
|
23
|
+
readonly phase: 'prepared' | 'dispatching' | 'outcome_unknown';
|
|
24
|
+
readonly declaredScopes: readonly unknown[];
|
|
25
|
+
readonly nativeProcess?: unknown;
|
|
26
|
+
}[];
|
|
27
|
+
readonly handles: readonly {
|
|
28
|
+
readonly handleId: string;
|
|
29
|
+
readonly toolCallId: string;
|
|
30
|
+
readonly state: 'active' | 'ended';
|
|
31
|
+
readonly metadata: Readonly<Record<string, unknown>>;
|
|
32
|
+
}[];
|
|
33
|
+
readonly usage: null | {
|
|
34
|
+
readonly usageScope: 'runtime_turn';
|
|
35
|
+
readonly providerRequestCount: number;
|
|
36
|
+
readonly inputTokens: number;
|
|
37
|
+
readonly outputTokens: number;
|
|
38
|
+
readonly cacheReadTokens: number;
|
|
39
|
+
readonly cacheWriteTokens: number;
|
|
40
|
+
readonly totalTokens: number;
|
|
41
|
+
};
|
|
42
|
+
readonly unknownUsage: boolean;
|
|
43
|
+
readonly attribution: Readonly<Record<string, unknown>>;
|
|
44
|
+
readonly usageCommitted: boolean;
|
|
45
|
+
readonly stop?: {
|
|
46
|
+
readonly owner: Recorder;
|
|
47
|
+
readonly observedAt: string;
|
|
48
|
+
readonly runnerIdle: true;
|
|
49
|
+
readonly admissionClosed: true;
|
|
50
|
+
readonly handlesEnded: true;
|
|
51
|
+
} | null;
|
|
52
|
+
readonly updatedAt: string;
|
|
53
|
+
}
|
|
54
|
+
/** Strict decoding: unknown versions/fields are preserved by the caller and block
|
|
55
|
+
* execution. Return a clone so a parser consumer cannot change the stored fact. */
|
|
56
|
+
export declare function normalizeConversationExecution(raw: unknown): ConversationExecution;
|
|
57
|
+
export declare function conversationExecutionPermitsNewRun(raw: unknown): boolean;
|
|
58
|
+
export {};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/** Ordinary execution facts in the original Conversation index. Shape is never
|
|
2
|
+
* permission, process-death proof, or authority to replay a pending dispatch. */
|
|
3
|
+
import { normalizeExecutionResourceScope } from "./session-control.js";
|
|
4
|
+
import { isHookObservation } from "./hook-observation.js";
|
|
5
|
+
import { nativeProcessEnvelopeValid } from "./native-process.js";
|
|
6
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
7
|
+
const keys = (v, allowed) => Object.keys(v).every(k => allowed.includes(k));
|
|
8
|
+
const text = (v, max) => typeof v === 'string' && v.trim().length > 0
|
|
9
|
+
&& new TextEncoder().encode(v).length <= max && !/[\u0000-\u001f\u007f-\u009f]/u.test(v);
|
|
10
|
+
const recorderKeys = ['bootId', 'pid', 'pidStart', 'hostId', 'acquiredAt'];
|
|
11
|
+
const recorder = (v) => object(v) && Object.keys(v).length === 5 && keys(v, recorderKeys)
|
|
12
|
+
&& Number.isInteger(v.pid) && v.pid > 0 && v.pid <= 2147483647
|
|
13
|
+
&& recorderKeys.filter(k => k !== 'pid').every(k => typeof v[k] === 'string' && v[k].length > 0
|
|
14
|
+
&& new TextEncoder().encode(v[k]).length <= 8192);
|
|
15
|
+
const sameRecorder = (a, b) => recorderKeys.every(k => a[k] === b[k]);
|
|
16
|
+
const safe = (v) => Number.isSafeInteger(v) && v >= 0;
|
|
17
|
+
const amountKeys = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens'];
|
|
18
|
+
const identity = (v) => object(v)
|
|
19
|
+
&& Object.keys(v).length === 3 && keys(v, ['kind', 'conversationId', 'streamId']) && v.kind === 'conversation'
|
|
20
|
+
&& typeof v.conversationId === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(v.conversationId) && text(v.streamId, 200);
|
|
21
|
+
function equalsRecord(a, b) {
|
|
22
|
+
if (!object(a) || !object(b))
|
|
23
|
+
return a === b;
|
|
24
|
+
const fields = Object.keys(a);
|
|
25
|
+
return fields.length === Object.keys(b).length && fields.every(k => Object.hasOwn(b, k) && equalsRecord(a[k], b[k]));
|
|
26
|
+
}
|
|
27
|
+
function validBackgroundShellHandle(h, metadata, run, runIdentity, owner, pending) {
|
|
28
|
+
const shell = metadata.nativeShell;
|
|
29
|
+
if (run.engine !== 'peer-native' || Object.keys(metadata).length !== 2 || !object(shell)
|
|
30
|
+
|| Object.keys(shell).length !== 2 || shell.schemaVersion !== 1)
|
|
31
|
+
return false;
|
|
32
|
+
const process = shell.process;
|
|
33
|
+
if (!object(process) || !nativeProcessEnvelopeValid(process) || !recorder(process.owner) || !sameRecorder(process.owner, owner)
|
|
34
|
+
|| !identity(process.execution) || !equalsRecord(process.execution, runIdentity)
|
|
35
|
+
|| typeof process.handleId !== 'string' || !/^shell_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(process.handleId)
|
|
36
|
+
|| !process.handleId.startsWith('shell_') || process.generation > 1
|
|
37
|
+
|| process.child != null && (!recorder(process.child) || process.child.pid === owner.pid)
|
|
38
|
+
|| h.handleId !== process.handleId || h.toolCallId !== process.toolCallId
|
|
39
|
+
|| h.state !== (process.state === 'ended' ? 'ended' : 'active'))
|
|
40
|
+
return false;
|
|
41
|
+
return pending.some(call => {
|
|
42
|
+
if (!object(call) || !object(call.nativeProcess) || call.toolCallId !== process.toolCallId || call.dispatchId !== process.dispatchId
|
|
43
|
+
|| call.capabilityId !== 'local.shell.exec' || call.phase === 'prepared')
|
|
44
|
+
return false;
|
|
45
|
+
const comparable = (value) => ({
|
|
46
|
+
...value, child: value.child ?? null, stopObservation: value.stopObservation ?? null,
|
|
47
|
+
});
|
|
48
|
+
return equalsRecord(comparable(call.nativeProcess), comparable(process));
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function validPersistentShellHandle(h, metadata, runIdentity, owner, pending) {
|
|
52
|
+
const session = metadata.nativeShellSession;
|
|
53
|
+
if (Object.keys(metadata).length !== 2 || !object(session)
|
|
54
|
+
|| Object.keys(session).length !== 3 || !keys(session, ['schemaVersion', 'process', 'command'])
|
|
55
|
+
|| session.schemaVersion !== 1 || !Object.hasOwn(session, 'command'))
|
|
56
|
+
return false;
|
|
57
|
+
const process = session.process;
|
|
58
|
+
if (!object(process) || !nativeProcessEnvelopeValid(process) || !recorder(process.owner)
|
|
59
|
+
|| !sameRecorder(process.owner, owner) || !identity(process.execution) || !equalsRecord(process.execution, runIdentity)
|
|
60
|
+
|| typeof process.handleId !== 'string' || !process.handleId.startsWith('shell-session_')
|
|
61
|
+
|| !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(process.handleId.slice('shell-session_'.length))
|
|
62
|
+
|| process.generation > 1 || process.child != null && (!recorder(process.child) || process.child.pid === owner.pid)
|
|
63
|
+
|| h.handleId !== process.handleId || h.toolCallId !== process.toolCallId
|
|
64
|
+
|| h.state !== (process.state === 'ended' ? 'ended' : 'active'))
|
|
65
|
+
return false;
|
|
66
|
+
const bound = (callId, dispatchId) => pending.some(call => object(call) && call.toolCallId === callId && call.dispatchId === dispatchId
|
|
67
|
+
&& call.capabilityId === 'local.shell.exec' && call.phase !== 'prepared' && call.nativeProcess == null);
|
|
68
|
+
if ((process.state === 'not_started' || process.state === 'starting')
|
|
69
|
+
&& !bound(process.toolCallId, process.dispatchId))
|
|
70
|
+
return false;
|
|
71
|
+
const command = session.command;
|
|
72
|
+
return command === null || object(command) && Object.keys(command).length === 3
|
|
73
|
+
&& keys(command, ['toolCallId', 'dispatchId', 'generation'])
|
|
74
|
+
&& ['running', 'ended'].some(state => state === process.state) && process.child != null
|
|
75
|
+
&& command.generation === process.generation && bound(command.toolCallId, command.dispatchId);
|
|
76
|
+
}
|
|
77
|
+
function validHookHandle(h, metadata, runIdentity, owner, pending) {
|
|
78
|
+
const hook = metadata.nativeHook;
|
|
79
|
+
if (Object.keys(metadata).length !== 2 || !object(hook)
|
|
80
|
+
|| !keys(hook, ['schemaVersion', 'event', 'ruleDigest', 'process', 'observation'])
|
|
81
|
+
|| hook.schemaVersion !== 1 || !['PreToolUse', 'PostToolUse'].some(v => v === hook.event)
|
|
82
|
+
|| typeof hook.ruleDigest !== 'string' || !/^[a-f0-9]{64}$/.test(hook.ruleDigest))
|
|
83
|
+
return false;
|
|
84
|
+
const p = hook.process;
|
|
85
|
+
if (!object(p) || !nativeProcessEnvelopeValid(p) || !recorder(p.owner)
|
|
86
|
+
|| !sameRecorder(p.owner, owner) || !identity(p.execution)
|
|
87
|
+
|| p.execution.conversationId !== runIdentity.conversationId || p.execution.streamId !== runIdentity.streamId
|
|
88
|
+
|| p.handleId !== h.handleId || p.toolCallId !== h.toolCallId
|
|
89
|
+
|| h.state !== (p.state === 'ended' ? 'ended' : 'active')
|
|
90
|
+
|| !safe(p.generation) || p.generation > 1 || p.child != null && !recorder(p.child)
|
|
91
|
+
|| !pending.some(row => object(row) && row.toolCallId === p.toolCallId && row.dispatchId === p.dispatchId
|
|
92
|
+
&& (hook.event === 'PreToolUse' || row.phase !== 'prepared')))
|
|
93
|
+
return false;
|
|
94
|
+
if (p.stopObservation !== 'owned_completion')
|
|
95
|
+
return !Object.hasOwn(hook, 'observation');
|
|
96
|
+
return isHookObservation(hook.observation, hook.event, hook.ruleDigest, p.handleId);
|
|
97
|
+
}
|
|
98
|
+
/** Strict decoding: unknown versions/fields are preserved by the caller and block
|
|
99
|
+
* execution. Return a clone so a parser consumer cannot change the stored fact. */
|
|
100
|
+
export function normalizeConversationExecution(raw) {
|
|
101
|
+
const invalid = () => { throw new Error('conversation_execution_invalid'); };
|
|
102
|
+
if (!object(raw) || !keys(raw, ['schemaVersion', 'identity', 'engine', 'owner', 'revision', 'phase', 'pendingTools',
|
|
103
|
+
'handles', 'usage', 'unknownUsage', 'attribution', 'usageCommitted', 'stop', 'updatedAt'])
|
|
104
|
+
|| raw.schemaVersion !== 1 || !identity(raw.identity) || !recorder(raw.owner)
|
|
105
|
+
|| !['peer-native', 'peer-ts'].some(v => v === raw.engine) || !safe(raw.revision) || raw.revision < 1
|
|
106
|
+
|| !['active', 'stopping', 'stopped', 'recovery_required'].some(v => v === raw.phase)
|
|
107
|
+
|| !text(raw.updatedAt, 64) || typeof raw.unknownUsage !== 'boolean' || typeof raw.usageCommitted !== 'boolean'
|
|
108
|
+
|| !Array.isArray(raw.pendingTools) || raw.pendingTools.length > 128 || !Array.isArray(raw.handles) || raw.handles.length > 128
|
|
109
|
+
|| !Object.hasOwn(raw, 'usage') || !object(raw.attribution) || raw.attribution.id !== raw.identity.streamId)
|
|
110
|
+
return invalid();
|
|
111
|
+
const at = raw.attribution;
|
|
112
|
+
if (!keys(at, ['id', 'at', 'streamId', 'modelProviderId', 'groupId', 'model', 'providerName', 'role', 'workspaceId', 'estimatedCostUsd', 'pricingSource'])
|
|
113
|
+
|| Object.entries(at).some(([k, v]) => v !== null && (k === 'estimatedCostUsd'
|
|
114
|
+
? typeof v !== 'number' || !Number.isFinite(v) || v < 0 : !text(v, 200)))
|
|
115
|
+
|| Object.hasOwn(at, 'streamId') && at.streamId !== raw.identity.streamId
|
|
116
|
+
|| at.role != null && at.role !== 'chat')
|
|
117
|
+
return invalid();
|
|
118
|
+
if (raw.usage !== null) {
|
|
119
|
+
const u = raw.usage;
|
|
120
|
+
if (!object(u) || Object.keys(u).length !== 7 || !keys(u, ['usageScope', 'providerRequestCount', ...amountKeys, 'totalTokens'])
|
|
121
|
+
|| u.usageScope !== 'runtime_turn' || !safe(u.providerRequestCount) || !safe(u.totalTokens)
|
|
122
|
+
|| !amountKeys.every(k => safe(u[k])) || amountKeys.reduce((n, k) => n + u[k], 0) !== u.totalTokens
|
|
123
|
+
|| u.totalTokens > 0 && u.providerRequestCount === 0)
|
|
124
|
+
return invalid();
|
|
125
|
+
}
|
|
126
|
+
if (raw.stop != null) {
|
|
127
|
+
const s = raw.stop;
|
|
128
|
+
if (!object(s) || !keys(s, ['owner', 'observedAt', 'runnerIdle', 'admissionClosed', 'handlesEnded']) || !recorder(s.owner)
|
|
129
|
+
|| !sameRecorder(s.owner, raw.owner) || !text(s.observedAt, 64) || s.runnerIdle !== true || s.admissionClosed !== true
|
|
130
|
+
|| s.handlesEnded !== true || ['active', 'stopping'].some(v => v === raw.phase))
|
|
131
|
+
return invalid();
|
|
132
|
+
}
|
|
133
|
+
else if (raw.phase === 'stopped')
|
|
134
|
+
return invalid();
|
|
135
|
+
if (raw.phase === 'stopped' && (raw.pendingTools.length !== 0 || !raw.usageCommitted))
|
|
136
|
+
return invalid();
|
|
137
|
+
const seen = [new Set(), new Set(), new Set()];
|
|
138
|
+
for (const p of raw.pendingTools) {
|
|
139
|
+
if (!object(p) || !keys(p, ['toolCallId', 'dispatchId', 'messageId', 'capabilityId', 'argsDigest', 'phase', 'declaredScopes', 'nativeProcess'])
|
|
140
|
+
|| !['toolCallId', 'dispatchId', 'messageId', 'capabilityId'].every(k => text(p[k], 200))
|
|
141
|
+
|| typeof p.argsDigest !== 'string' || !/^[a-f0-9]{64}$/.test(p.argsDigest)
|
|
142
|
+
|| !['prepared', 'dispatching', 'outcome_unknown'].some(v => v === p.phase) || !Array.isArray(p.declaredScopes)
|
|
143
|
+
|| p.declaredScopes.length > 32 || p.declaredScopes.some(s => !normalizeExecutionResourceScope(s)))
|
|
144
|
+
return invalid();
|
|
145
|
+
for (const [i, k] of ['toolCallId', 'dispatchId', 'messageId'].entries()) {
|
|
146
|
+
const v = p[k];
|
|
147
|
+
if (seen[i].has(v))
|
|
148
|
+
return invalid();
|
|
149
|
+
seen[i].add(v);
|
|
150
|
+
}
|
|
151
|
+
if (p.nativeProcess != null) {
|
|
152
|
+
const n = p.nativeProcess;
|
|
153
|
+
if (p.phase === 'prepared' || !object(n) || !nativeProcessEnvelopeValid(n) || !recorder(n.owner)
|
|
154
|
+
|| !sameRecorder(n.owner, raw.owner) || !identity(n.execution) || n.execution.conversationId !== raw.identity.conversationId
|
|
155
|
+
|| n.execution.streamId !== raw.identity.streamId || n.toolCallId !== p.toolCallId || n.dispatchId !== p.dispatchId
|
|
156
|
+
|| n.child != null && !recorder(n.child))
|
|
157
|
+
return invalid();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const handles = new Set();
|
|
161
|
+
let shellSessionSeen = false;
|
|
162
|
+
for (const h of raw.handles) {
|
|
163
|
+
if (!object(h) || Object.keys(h).length !== 4 || !keys(h, ['handleId', 'toolCallId', 'state', 'metadata'])
|
|
164
|
+
|| !text(h.handleId, 512) || handles.has(h.handleId) || !text(h.toolCallId, 200) || !object(h.metadata)
|
|
165
|
+
|| !['active', 'ended'].some(v => v === h.state) || raw.phase === 'stopped' && h.state !== 'ended')
|
|
166
|
+
return invalid();
|
|
167
|
+
if (h.metadata.kind === 'hook' && !validHookHandle(h, h.metadata, raw.identity, raw.owner, raw.pendingTools))
|
|
168
|
+
return invalid();
|
|
169
|
+
if (h.metadata.kind === 'shell_background' && !validBackgroundShellHandle(h, h.metadata, raw, raw.identity, raw.owner, raw.pendingTools))
|
|
170
|
+
return invalid();
|
|
171
|
+
if (h.metadata.kind === 'shell_session') {
|
|
172
|
+
if (shellSessionSeen || !validPersistentShellHandle(h, h.metadata, raw.identity, raw.owner, raw.pendingTools))
|
|
173
|
+
return invalid();
|
|
174
|
+
shellSessionSeen = true;
|
|
175
|
+
}
|
|
176
|
+
handles.add(h.handleId);
|
|
177
|
+
}
|
|
178
|
+
return structuredClone(raw);
|
|
179
|
+
}
|
|
180
|
+
export function conversationExecutionPermitsNewRun(raw) {
|
|
181
|
+
const r = normalizeConversationExecution(raw);
|
|
182
|
+
return r.phase === 'stopped' && r.pendingTools.length === 0 && r.usageCommitted;
|
|
183
|
+
}
|
package/dist/delegation.d.ts
CHANGED
|
@@ -95,6 +95,7 @@ export interface WorkSessionConversationMeta extends SessionQueueFacts {
|
|
|
95
95
|
readonly resultConfirmationRequired?: boolean;
|
|
96
96
|
readonly accepted?: boolean;
|
|
97
97
|
readonly verifying?: boolean;
|
|
98
|
+
readonly verificationFailed?: boolean;
|
|
98
99
|
readonly phase?: 'starting' | 'verifying' | 'paused';
|
|
99
100
|
/** 进程内执行所有权(runtime 采集);缺省表示该入口尚未接入所有权事实。 */
|
|
100
101
|
readonly executionOwnership?: ExecutionOwnership;
|
|
@@ -138,6 +139,11 @@ export interface SessionReport {
|
|
|
138
139
|
readonly summary: string;
|
|
139
140
|
}[];
|
|
140
141
|
readonly evidenceRefs: readonly string[];
|
|
142
|
+
readonly failure?: {
|
|
143
|
+
readonly code: string;
|
|
144
|
+
readonly message?: string;
|
|
145
|
+
readonly at?: string;
|
|
146
|
+
};
|
|
141
147
|
/** Persisted worker output is a claim; verification still comes from host Evidence. */
|
|
142
148
|
readonly contentSource?: {
|
|
143
149
|
readonly kind: 'worker_message' | 'task_results';
|
|
@@ -316,6 +322,8 @@ export interface SessionVerificationDetail {
|
|
|
316
322
|
readonly workerModel: string | null;
|
|
317
323
|
readonly verifierModel: string | null;
|
|
318
324
|
readonly sameSource: boolean;
|
|
325
|
+
readonly summary?: string;
|
|
326
|
+
readonly error?: string;
|
|
319
327
|
readonly reviewAttempts: readonly VerificationAttemptDiagnostic[];
|
|
320
328
|
readonly outputs: readonly {
|
|
321
329
|
readonly name: string;
|
package/dist/delegation.js
CHANGED
|
@@ -66,6 +66,7 @@ export function projectWorkSession(plan, conversationMeta) {
|
|
|
66
66
|
superseded: Boolean(conversationMeta.supersededBy),
|
|
67
67
|
needsUser: plan.status === 'awaiting_approval' || plan.needsUser === true,
|
|
68
68
|
verificationActive: conversationMeta.verifying === true,
|
|
69
|
+
...(conversationMeta.verificationFailed === true ? { verificationFailed: true } : {}),
|
|
69
70
|
...(conversationMeta.phase ? { phase: conversationMeta.phase } : {}),
|
|
70
71
|
blockedReason: plan.agentWaiting ? 'waiting_parent_agent' : plan.blockedReason,
|
|
71
72
|
interrupted: plan.interrupted,
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The structured observation shared by Conversation and Work. */
|
|
2
|
+
export function isHookObservation(input, event, ruleDigest, handleId) {
|
|
3
|
+
const note = (value) => typeof value === 'string'
|
|
4
|
+
&& new TextEncoder().encode(value).length <= 1024
|
|
5
|
+
&& !/[\u0000-\u001f\u007f-\u009f]/u.test(value);
|
|
6
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
7
|
+
return false;
|
|
8
|
+
const value = input;
|
|
9
|
+
return Object.keys(value).length === 10
|
|
10
|
+
&& value.event === event && value.ruleDigest === ruleDigest && value.handleId === handleId
|
|
11
|
+
&& ['allow', 'ask', 'deny'].some(decision => decision === value.decision)
|
|
12
|
+
&& typeof value.outcome === 'string' && value.outcome.length > 0
|
|
13
|
+
&& new TextEncoder().encode(value.outcome).length <= 128
|
|
14
|
+
&& (value.exitCode === null || typeof value.exitCode === 'number' && Number.isInteger(value.exitCode)
|
|
15
|
+
&& value.exitCode >= -2147483648 && value.exitCode <= 2147483647)
|
|
16
|
+
&& Number.isSafeInteger(value.durationMs) && value.durationMs >= 0
|
|
17
|
+
&& note(value.id) && value.hookId === value.id
|
|
18
|
+
&& (value.reason === null || note(value.reason));
|
|
19
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
export { WORK_HOOK_SEMANTIC_FLOOR, nativeWorkHasHookFacts } from './work-hook.ts';
|
|
1
2
|
export type { AttentionCard, BotDecisionSnapshot, BotAttentionItem, BotAttentionRequest, BotAttentionResult } from './attention.ts';
|
|
2
|
-
export type { ProjectWorkBudgetLimits, ProjectWorkBudgetBoundary, ProjectReplyRecoveryAction, ProjectWorkReceipt, ProjectWorkRecovery, ProjectWorkState, ProjectTurnEnd, ProjectReplyFailureStatus, ProjectAgentSilentWait, } from './work-coordination.ts';
|
|
3
|
+
export type { ProjectWorkBudgetLimits, NativeEpisodeRecorder, ProjectWorkBudgetBoundary, ProjectReplyRecoveryAction, ProjectWorkReceipt, ProjectWorkRecovery, ProjectWorkState, ProjectTurnEnd, ProjectReplyFailureStatus, ProjectAgentSilentWait, } from './work-coordination.ts';
|
|
3
4
|
export type { CoordinationAction, CoordinationLifecycle, CoordinationMandate, CoordinationDecision, TaskTransitionPhase, TaskTransition, CoordinationExecutionBinding, CoordinationSessionFacts, } from './delegation-coordination.ts';
|
|
4
5
|
export { deriveSessionFacts, type SessionFactSnapshot } from './session-facts.ts';
|
|
5
6
|
export { runtimeSessionFacts, runtimeSessionOwnership, hasPendingRuntimeSessions } from './runtime-session-facts.ts';
|
|
@@ -20,7 +21,7 @@ export { REMOTE_PROJECT_LIMITS, parseRemoteProjectRequest, admitRemoteProject, p
|
|
|
20
21
|
export type { RemoteProjectGrant, RemoteProjectRequest, RemoteProjectInteractiveResult, RemoteProjectContext, RemoteProjectRejection, RemoteProjectAdmission, RemoteDelegationProjection, } from './remote-access.ts';
|
|
21
22
|
export type LocalAccessLevel = 'ask_before_local' | 'session_local' | 'restricted_local' | 'full_local';
|
|
22
23
|
export type { BotAccessPolicy, BotAccessPolicyReadRequest, BotAccessPolicyUpdateRequest, BotAccessPolicyResult } from './bot-access-policy.ts';
|
|
23
|
-
export type { ConversationLifetimeUsage, ProviderRequestUsage, RuntimeTurnUsage, UsageAmounts, UsageScope, } from './usage-accounting.ts';
|
|
24
|
+
export type { ConversationLifetimeUsage, ProviderRequestUsage, RuntimeTurnUsage, NativeRuntimeUsageSnapshot, NativeUsageRecoveryProgress, UsageAmounts, UsageScope, } from './usage-accounting.ts';
|
|
24
25
|
export type CapabilityRiskLevel = 'L0_inert' | 'L1_local_read' | 'L2_local_write' | 'L3_external_write' | 'L4_privileged' | 'L5_destructive';
|
|
25
26
|
export type DataLevel = 'D0_public' | 'D1_internal' | 'D2_sensitive' | 'D3_private' | 'D4_regulated';
|
|
26
27
|
export type CapabilitySource = 'native' | 'shell' | 'plugin' | 'mcp' | 'page_bridge' | 'private' | 'web';
|
|
@@ -162,7 +163,7 @@ export interface McpCredentialMetadataView {
|
|
|
162
163
|
readonly createdAt: string;
|
|
163
164
|
readonly updatedAt: string;
|
|
164
165
|
readonly lastFour?: string;
|
|
165
|
-
readonly storage?: 'safeStorage' | 'file-fallback';
|
|
166
|
+
readonly storage?: 'safeStorage' | 'file-fallback' | 'vault';
|
|
166
167
|
}
|
|
167
168
|
export interface McpCredentialPutRequest {
|
|
168
169
|
readonly credentialRef?: string;
|
|
@@ -233,6 +234,12 @@ export interface LocalMcpServerView {
|
|
|
233
234
|
readonly resources: readonly McpResourceSummary[];
|
|
234
235
|
readonly prompts: readonly McpPromptSummary[];
|
|
235
236
|
readonly health: McpHealthView;
|
|
237
|
+
readonly policy?: {
|
|
238
|
+
readonly trusted?: boolean;
|
|
239
|
+
readonly requirePermission?: boolean;
|
|
240
|
+
readonly visibleByDefault?: boolean;
|
|
241
|
+
readonly maxRiskLevel?: string;
|
|
242
|
+
};
|
|
236
243
|
readonly manifestUpdatedAt?: string | null;
|
|
237
244
|
readonly lastError?: string | null;
|
|
238
245
|
readonly createdAt?: string;
|
|
@@ -336,7 +343,7 @@ export interface WorkspaceProject {
|
|
|
336
343
|
readonly updatedAt: string;
|
|
337
344
|
}
|
|
338
345
|
export type LlmProviderType = 'openai' | 'anthropic';
|
|
339
|
-
export type LlmWireProtocol = 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'gemini'
|
|
346
|
+
export type LlmWireProtocol = 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'gemini';
|
|
340
347
|
export type LlmChannelId = string;
|
|
341
348
|
export type LlmReasoningParamStyle = 'openai-effort' | 'anthropic-enabled-budget' | 'anthropic-adaptive-effort' | 'anthropic-output-effort' | 'qwen-enable' | 'none';
|
|
342
349
|
export type LlmReasoningEffortMap = Readonly<Record<string, string | number>>;
|
|
@@ -434,7 +441,7 @@ export interface LlmChannelDescriptor {
|
|
|
434
441
|
/** 可选:将该 channel 映射到一个或多个服务模板(添加服务目录)。 */
|
|
435
442
|
readonly serviceTemplates?: readonly LlmServiceTemplateDescriptor[];
|
|
436
443
|
}
|
|
437
|
-
export type LlmAuthMethod = 'api_key' | 'oauth_chatgpt' | '
|
|
444
|
+
export type LlmAuthMethod = 'api_key' | 'oauth_chatgpt' | 'oauth_grok';
|
|
438
445
|
export type LlmOAuthConnectionStatus = 'connected' | 'expired' | 'disconnected';
|
|
439
446
|
export interface LlmOAuthStatus {
|
|
440
447
|
readonly status: LlmOAuthConnectionStatus;
|
|
@@ -457,7 +464,6 @@ export interface LlmSubscriptionQuotaWindow {
|
|
|
457
464
|
readonly scope?: import('./account-usage.js').AccountUsageScope;
|
|
458
465
|
}
|
|
459
466
|
/**
|
|
460
|
-
* GPT / Gemini / Grok / Qoder 订阅额度快照。
|
|
461
467
|
* success=false 时用 status/error 表达未登录、过期或拉取失败,UI 应降级展示。
|
|
462
468
|
*/
|
|
463
469
|
export interface LlmSubscriptionQuota {
|
|
@@ -474,22 +480,16 @@ export interface LlmSubscriptionQuota {
|
|
|
474
480
|
readonly status?: string;
|
|
475
481
|
readonly providerId?: string;
|
|
476
482
|
readonly authMethod?: LlmAuthMethod;
|
|
477
|
-
readonly provider?: 'chatgpt' | '
|
|
483
|
+
readonly provider?: 'chatgpt' | 'grok';
|
|
478
484
|
readonly planLabel?: string;
|
|
479
485
|
readonly remainingPercent?: number;
|
|
480
486
|
readonly usedPercent?: number;
|
|
481
487
|
readonly resetsAt?: string;
|
|
482
488
|
readonly windows?: readonly LlmSubscriptionQuotaWindow[];
|
|
483
489
|
readonly accountId?: string;
|
|
484
|
-
readonly projectId?: string;
|
|
485
490
|
readonly fetchedAt?: string;
|
|
486
491
|
readonly cached?: boolean;
|
|
487
492
|
readonly error?: string;
|
|
488
|
-
readonly availableCredits?: number;
|
|
489
|
-
readonly planCreditsUsed?: number;
|
|
490
|
-
readonly planCreditsTotal?: number;
|
|
491
|
-
readonly orgPackageUsed?: number;
|
|
492
|
-
readonly orgPackageCap?: number;
|
|
493
493
|
}
|
|
494
494
|
export interface LlmProviderConfig {
|
|
495
495
|
readonly id: string;
|
|
@@ -529,7 +529,6 @@ export interface LlmProviderConfig {
|
|
|
529
529
|
readonly reasoningEffortLevels?: readonly string[];
|
|
530
530
|
/** 渠道默认思考强度(如 Grok 为 high)。UI 切模型时用于落到正确默认档。 */
|
|
531
531
|
readonly reasoningDefaultEffort?: string;
|
|
532
|
-
readonly oauthProjectId?: string;
|
|
533
532
|
readonly customHeaders?: Readonly<Record<string, string>>;
|
|
534
533
|
readonly customHeadersInvalid?: boolean;
|
|
535
534
|
/**
|
|
@@ -593,7 +592,6 @@ export interface LlmProviderGroupConfig {
|
|
|
593
592
|
readonly name: string;
|
|
594
593
|
readonly baseUrl: string;
|
|
595
594
|
readonly createdAt: string;
|
|
596
|
-
readonly oauthProjectId?: string;
|
|
597
595
|
readonly models: readonly LlmModelConfig[];
|
|
598
596
|
}
|
|
599
597
|
export interface LlmProviderGroupConfigView extends LlmProviderGroupConfig {
|
|
@@ -643,8 +641,6 @@ export interface LlmModelInfo {
|
|
|
643
641
|
readonly longContextInputPrice?: number;
|
|
644
642
|
readonly longContextCacheReadPrice?: number;
|
|
645
643
|
readonly longContextOutputPrice?: number;
|
|
646
|
-
readonly priceFactor?: number;
|
|
647
|
-
readonly originalPriceFactor?: number;
|
|
648
644
|
}
|
|
649
645
|
export interface LlmModelListResult {
|
|
650
646
|
readonly success: boolean;
|
|
@@ -655,7 +651,6 @@ export interface LlmModelListResult {
|
|
|
655
651
|
export interface LlmModelFetchRequest {
|
|
656
652
|
readonly channelId?: string;
|
|
657
653
|
readonly wireOverride?: string;
|
|
658
|
-
/** Qoder 私有接口等本机鉴权渠道需要显式传入,避免 fetch 路径被默认当成 api_key。 */
|
|
659
654
|
readonly authMethod?: LlmAuthMethod;
|
|
660
655
|
readonly baseUrl?: string;
|
|
661
656
|
readonly apiKey?: string;
|
|
@@ -763,7 +758,7 @@ export interface PermissionGrant {
|
|
|
763
758
|
readonly toolCallId: string;
|
|
764
759
|
readonly granted: boolean;
|
|
765
760
|
readonly duration: PermissionDuration;
|
|
766
|
-
readonly scope?: string | import('./local-image.ts').LocalImagePermissionScope;
|
|
761
|
+
readonly scope?: string | import('./local-image.ts').LocalImagePermissionScope | import('./local-read.ts').LocalReadPermissionScope;
|
|
767
762
|
readonly decidedAt: string;
|
|
768
763
|
}
|
|
769
764
|
/** Application-owned shell process snapshot. Source conversation is provenance, not ownership. */
|
|
@@ -853,6 +848,21 @@ export interface Evidence {
|
|
|
853
848
|
readonly dataLevel: DataLevel;
|
|
854
849
|
readonly redactions: readonly string[];
|
|
855
850
|
readonly artifactRefs: readonly string[];
|
|
851
|
+
/** Host/Provider observation before tools/call; never read from server output. */
|
|
852
|
+
readonly dispatchOutcome?: 'not_dispatched';
|
|
853
|
+
}
|
|
854
|
+
/** Native MCP attempt metadata, including denials and failed initialization. */
|
|
855
|
+
export interface NativeMcpToolEvidenceMetadata {
|
|
856
|
+
readonly evidenceKind: 'local_mcp_tool_call';
|
|
857
|
+
readonly serverId: string;
|
|
858
|
+
readonly providerId: string;
|
|
859
|
+
readonly transport: 'stdio' | 'streamable_http' | 'sse';
|
|
860
|
+
readonly toolName: string;
|
|
861
|
+
readonly projectionId: string;
|
|
862
|
+
readonly permissionGrantId: string;
|
|
863
|
+
readonly status: 'success' | 'denied' | 'failed' | 'cancelled';
|
|
864
|
+
readonly startedAt: string;
|
|
865
|
+
readonly endedAt: string;
|
|
856
866
|
}
|
|
857
867
|
export interface ClientToolResult {
|
|
858
868
|
readonly toolCallId: string;
|
|
@@ -899,6 +909,8 @@ export * from './objectives.ts';
|
|
|
899
909
|
export * from './remote-access-settings.ts';
|
|
900
910
|
export type { BotModelSelectionUpdateRequest, BotModelSelectionUpdateResult } from './bot-model-selection.ts';
|
|
901
911
|
export * from './local-image.ts';
|
|
912
|
+
export * from './local-read.ts';
|
|
913
|
+
export * from './native-process.ts';
|
|
902
914
|
export * from './bot-conversation-read.ts';
|
|
903
915
|
export * from './project-recovery.ts';
|
|
904
916
|
export * from './local-git.ts';
|
|
@@ -921,3 +933,5 @@ export { controlPhasesForOrigin, normalizeSessionExecutionIdentity, normalizeExe
|
|
|
921
933
|
export * from './input-prediction.ts';
|
|
922
934
|
export * from './interactive-result.ts';
|
|
923
935
|
export * from './interactive-verification.ts';
|
|
936
|
+
export { normalizeConversationExecution, conversationExecutionPermitsNewRun } from './conversation-execution.ts';
|
|
937
|
+
export type { ConversationExecutionIdentity, ConversationExecution } from './conversation-execution.ts';
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { WORK_HOOK_SEMANTIC_FLOOR, nativeWorkHasHookFacts } from "./work-hook.js";
|
|
1
2
|
export { deriveSessionFacts } from "./session-facts.js";
|
|
2
3
|
export { runtimeSessionFacts, runtimeSessionOwnership, hasPendingRuntimeSessions } from "./runtime-session-facts.js";
|
|
3
4
|
export { projectAgentFailureKind, classifyProjectAgentFailure } from "./project-agent-failure.js";
|
|
@@ -44,6 +45,8 @@ export * from "./project.js";
|
|
|
44
45
|
export * from "./objectives.js";
|
|
45
46
|
export * from "./remote-access-settings.js";
|
|
46
47
|
export * from "./local-image.js";
|
|
48
|
+
export * from "./local-read.js";
|
|
49
|
+
export * from "./native-process.js";
|
|
47
50
|
export * from "./bot-conversation-read.js";
|
|
48
51
|
export * from "./project-recovery.js";
|
|
49
52
|
export * from "./local-git.js";
|
|
@@ -62,3 +65,4 @@ export { controlPhasesForOrigin, normalizeSessionExecutionIdentity, normalizeExe
|
|
|
62
65
|
export * from "./input-prediction.js";
|
|
63
66
|
export * from "./interactive-result.js";
|
|
64
67
|
export * from "./interactive-verification.js";
|
|
68
|
+
export { normalizeConversationExecution, conversationExecutionPermitsNewRun } from "./conversation-execution.js";
|
|
@@ -11,11 +11,11 @@ export interface InputPredictionSettings {
|
|
|
11
11
|
}
|
|
12
12
|
export declare const INPUT_PREDICTION_LIMITS: Readonly<{
|
|
13
13
|
inputTokens: 4096;
|
|
14
|
-
outputTokens:
|
|
14
|
+
outputTokens: 256;
|
|
15
15
|
draftLength: 2048;
|
|
16
16
|
candidateLength: 240;
|
|
17
17
|
candidateGraphemes: 120;
|
|
18
|
-
timeoutMs:
|
|
18
|
+
timeoutMs: 6000;
|
|
19
19
|
validationMs: 150;
|
|
20
20
|
ttlMs: 60000;
|
|
21
21
|
requestIntervalMs: 3000;
|
package/dist/input-prediction.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export const INPUT_PREDICTION_LIMITS = Object.freeze({
|
|
2
|
-
inputTokens: 4096, outputTokens:
|
|
2
|
+
inputTokens: 4096, outputTokens: 256, draftLength: 2048,
|
|
3
3
|
candidateLength: 240, candidateGraphemes: 120,
|
|
4
|
-
timeoutMs:
|
|
4
|
+
timeoutMs: 6000, validationMs: 150, ttlMs: 60_000,
|
|
5
5
|
requestIntervalMs: 3000, requestsPerMinute: 12,
|
|
6
6
|
});
|
|
7
7
|
export function normalizeInputPredictionSettings(value) {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** ADR106/131: the existing Git Provider's concrete local read approval shape.
|
|
2
|
+
* This is an audit scope, never a deserializable execution authority token.
|
|
3
|
+
*/
|
|
4
|
+
export interface LocalReadPermissionScope {
|
|
5
|
+
readonly kind: 'file-read';
|
|
6
|
+
readonly capabilityId: string;
|
|
7
|
+
readonly path: string;
|
|
8
|
+
readonly workspacePath: string | null;
|
|
9
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { SessionControlOperation } from './session-control.ts';
|
|
2
|
+
import { type SessionExecutionIdentity } from './session-control.ts';
|
|
3
|
+
type Recorder = NonNullable<SessionControlOperation['recorder']>;
|
|
4
|
+
export interface NativeOwnedProcess {
|
|
5
|
+
readonly schemaVersion: 1;
|
|
6
|
+
readonly kind: 'command';
|
|
7
|
+
readonly handleId: string;
|
|
8
|
+
readonly toolCallId: string;
|
|
9
|
+
readonly dispatchId: string;
|
|
10
|
+
readonly execution: SessionExecutionIdentity;
|
|
11
|
+
readonly generation: number;
|
|
12
|
+
readonly state: 'not_started' | 'starting' | 'running' | 'ended';
|
|
13
|
+
readonly owner: Recorder;
|
|
14
|
+
readonly child?: Recorder | null;
|
|
15
|
+
readonly stopObservation?: 'owned_completion' | 'owner_dead_not_started' | 'owner_dead_group_absent' | null;
|
|
16
|
+
}
|
|
17
|
+
/** Envelope shape only. Execution identity is validated by each owning contract. */
|
|
18
|
+
export declare function nativeProcessEnvelopeValid(raw: unknown): boolean;
|
|
19
|
+
/** Shape only: no value here proves local execution or process death. */
|
|
20
|
+
export declare function nativeProcessesInWork(work: unknown): readonly NativeOwnedProcess[];
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { normalizeSessionExecutionIdentity } from "./session-control.js";
|
|
2
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
3
|
+
const text = (v, bytes) => typeof v === 'string' && v.length > 0 && v.length <= bytes && new TextEncoder().encode(v).length <= bytes;
|
|
4
|
+
const recorder = (v) => {
|
|
5
|
+
const r = object(v);
|
|
6
|
+
return Number.isInteger(r.pid) && r.pid > 0 && r.pid <= 2147483647
|
|
7
|
+
&& ['bootId', 'pidStart', 'hostId', 'acquiredAt'].every(k => text(r[k], 8192));
|
|
8
|
+
};
|
|
9
|
+
/** Envelope shape only. Execution identity is validated by each owning contract. */
|
|
10
|
+
export function nativeProcessEnvelopeValid(raw) {
|
|
11
|
+
const p = object(raw), owner = object(p.owner), child = object(p.child);
|
|
12
|
+
const keys = ['schemaVersion', 'kind', 'handleId', 'toolCallId', 'dispatchId', 'execution', 'generation', 'state', 'owner', 'child', 'stopObservation'];
|
|
13
|
+
const validChild = p.child == null || recorder(child) && ['hostId', 'acquiredAt', 'bootId'].every(k => child[k] === owner[k]);
|
|
14
|
+
const gen = Number.isInteger(p.generation) && p.generation >= 0 && p.generation <= 64;
|
|
15
|
+
const phase = p.state === 'not_started' ? p.generation === 0 && p.child == null && p.stopObservation == null
|
|
16
|
+
: p.state === 'starting' ? p.generation > 0 && p.child == null && p.stopObservation == null
|
|
17
|
+
: p.state === 'running' ? p.generation > 0 && p.child != null && p.stopObservation == null
|
|
18
|
+
: p.state === 'ended' && (p.stopObservation === 'owned_completion'
|
|
19
|
+
|| p.stopObservation === 'owner_dead_not_started' && p.generation === 0 && p.child == null
|
|
20
|
+
|| p.stopObservation === 'owner_dead_group_absent' && p.generation > 0 && p.child != null);
|
|
21
|
+
return p.schemaVersion === 1 && p.kind === 'command' && !Object.keys(p).some(k => !keys.includes(k))
|
|
22
|
+
&& ['handleId', 'toolCallId', 'dispatchId'].every(k => text(p[k], 200))
|
|
23
|
+
&& !!gen && !!phase && recorder(owner) && !!validChild;
|
|
24
|
+
}
|
|
25
|
+
/** Shape only: no value here proves local execution or process death. */
|
|
26
|
+
export function nativeProcessesInWork(work) {
|
|
27
|
+
const budget = object(object(work).budget);
|
|
28
|
+
const rows = [...Object.values(object(budget.attempts)).flatMap(a => {
|
|
29
|
+
const pending = object(a).pendingTools;
|
|
30
|
+
return Array.isArray(pending) ? pending : [];
|
|
31
|
+
}), ...(Array.isArray(budget.uncertainDispatches) ? budget.uncertainDispatches : [])];
|
|
32
|
+
const result = [];
|
|
33
|
+
for (const raw of rows) {
|
|
34
|
+
const row = object(raw);
|
|
35
|
+
if (!Object.hasOwn(row, 'nativeProcess'))
|
|
36
|
+
continue;
|
|
37
|
+
const p = object(row.nativeProcess), owner = object(p.owner);
|
|
38
|
+
const original = object(object(row.nativeRecorder).recorder);
|
|
39
|
+
const execution = normalizeSessionExecutionIdentity(p.execution);
|
|
40
|
+
const recordedExecution = normalizeSessionExecutionIdentity(object(row.nativeRecorder).execution);
|
|
41
|
+
if (!nativeProcessEnvelopeValid(p) || !recorder(original) || !execution || !recordedExecution
|
|
42
|
+
|| JSON.stringify(execution) !== JSON.stringify(recordedExecution)
|
|
43
|
+
|| !['pid', 'pidStart', 'bootId', 'hostId', 'acquiredAt'].every(k => owner[k] === original[k])
|
|
44
|
+
|| p.toolCallId !== row.toolCallId || p.dispatchId !== row.dispatchId || result.length >= 128
|
|
45
|
+
|| result.some(old => old.handleId === p.handleId || old.toolCallId === p.toolCallId || old.dispatchId === p.dispatchId)) {
|
|
46
|
+
throw new Error('native_process_invalid');
|
|
47
|
+
}
|
|
48
|
+
result.push(structuredClone(p));
|
|
49
|
+
}
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
import type { ResourceFeedback } from './resource-feedback.ts';
|
|
2
|
-
import type { ProjectInputAttachment, ProjectAgentSubmitInputResult } from './delegation.ts';
|
|
2
|
+
import type { ProjectInputAttachment, ProjectAgentSubmitInputResult, WorkSessionStatus } from './delegation.ts';
|
|
3
3
|
export type LocalInputSurface = 'desktop' | 'quick_chat' | 'tui';
|
|
4
4
|
export interface InputDraftQuote {
|
|
5
5
|
readonly messageId: string;
|
|
6
6
|
readonly text: string;
|
|
7
7
|
}
|
|
8
|
+
export interface InputDraftTaskRef {
|
|
9
|
+
readonly sessionId: string;
|
|
10
|
+
readonly title: string;
|
|
11
|
+
readonly status: WorkSessionStatus | string;
|
|
12
|
+
readonly anchorMessageId?: string;
|
|
13
|
+
}
|
|
8
14
|
export interface InputDraftValue {
|
|
9
15
|
readonly text: string;
|
|
10
16
|
readonly quote: InputDraftQuote | null;
|
|
11
17
|
readonly attachments: readonly ProjectInputAttachment[];
|
|
18
|
+
readonly taskRefs?: readonly InputDraftTaskRef[];
|
|
12
19
|
readonly resourceFeedback?: readonly ResourceFeedback[];
|
|
13
20
|
}
|
|
14
21
|
/** User intent only. Presence here never means the input was received or executed. */
|
|
@@ -16,6 +23,7 @@ export interface UnconfirmedProjectInput {
|
|
|
16
23
|
readonly inputId: string;
|
|
17
24
|
readonly text: string;
|
|
18
25
|
readonly quoteRefs: readonly string[];
|
|
26
|
+
readonly taskRefs?: readonly InputDraftTaskRef[];
|
|
19
27
|
readonly answerTo?: string;
|
|
20
28
|
readonly attachments: readonly ProjectInputAttachment[];
|
|
21
29
|
readonly resourceFeedback?: readonly ResourceFeedback[];
|
package/dist/project.d.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import type { ProjectModelPolicy } from './model-routing.ts';
|
|
6
6
|
import type { PendingApprovalState, WorkSessionStatus } from './delegation.ts';
|
|
7
|
+
import type { FollowUpProjection } from './task-overview.ts';
|
|
7
8
|
export interface DiagnosticText {
|
|
8
9
|
readonly length: number;
|
|
9
10
|
readonly sha256: string;
|
|
@@ -133,11 +134,25 @@ export type ProjectHostTakeoverResult = {
|
|
|
133
134
|
readonly ok: false;
|
|
134
135
|
readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'HOST_UNAVAILABLE' | 'INVALID_INPUT';
|
|
135
136
|
};
|
|
137
|
+
export declare const BOT_AVATAR_HEADS: readonly ["none", "beret", "glasses", "beanie", "vermeer", "straw", "headphones", "crown"];
|
|
138
|
+
export type BotAvatarHead = (typeof BOT_AVATAR_HEADS)[number];
|
|
139
|
+
export declare const BOT_AVATAR_NECKS: readonly ["bowtie", "scarf", "sweater", "moon", "sailor", "cape"];
|
|
140
|
+
export type BotAvatarNeck = (typeof BOT_AVATAR_NECKS)[number];
|
|
141
|
+
export interface BotAvatarPartsPatch {
|
|
142
|
+
readonly shape?: string;
|
|
143
|
+
readonly color?: string;
|
|
144
|
+
readonly head?: BotAvatarHead;
|
|
145
|
+
readonly neck?: BotAvatarNeck;
|
|
146
|
+
readonly backdrop?: boolean;
|
|
147
|
+
}
|
|
136
148
|
export type BotAvatar = {
|
|
137
149
|
readonly kind: 'generated';
|
|
138
150
|
readonly shape: string;
|
|
139
151
|
readonly color: string;
|
|
140
152
|
readonly variant?: number;
|
|
153
|
+
readonly head?: BotAvatarHead;
|
|
154
|
+
readonly neck?: BotAvatarNeck;
|
|
155
|
+
readonly backdrop?: boolean;
|
|
141
156
|
} | {
|
|
142
157
|
readonly kind: 'image';
|
|
143
158
|
readonly ref: string;
|
|
@@ -149,6 +164,19 @@ export type BotAvatarReadResult = {
|
|
|
149
164
|
readonly ok: false;
|
|
150
165
|
readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'INVALID_IMAGE';
|
|
151
166
|
};
|
|
167
|
+
export type BotCommunicationStyle = 'natural' | 'concise' | 'detailed' | 'technical';
|
|
168
|
+
export type BotProfileCommunicationStyle = 'inherit' | BotCommunicationStyle;
|
|
169
|
+
/** Per-bot capability mounting overrides (inherits global enabled state when absent). */
|
|
170
|
+
export interface BotCapabilityPolicy {
|
|
171
|
+
/** Skill IDs explicitly mounted on this bot (overrides global disable). */
|
|
172
|
+
readonly enabledSkillIds?: readonly string[];
|
|
173
|
+
/** Skill IDs explicitly unmounted on this bot (overrides global/workspace enable). */
|
|
174
|
+
readonly disabledSkillIds?: readonly string[];
|
|
175
|
+
/** MCP server IDs explicitly mounted on this bot (overrides global disable). */
|
|
176
|
+
readonly enabledMcpIds?: readonly string[];
|
|
177
|
+
/** MCP server IDs explicitly unmounted on this bot (overrides global enable). */
|
|
178
|
+
readonly disabledMcpIds?: readonly string[];
|
|
179
|
+
}
|
|
152
180
|
export interface BotProfile {
|
|
153
181
|
readonly workspaceId: string;
|
|
154
182
|
readonly displayName: string;
|
|
@@ -156,6 +184,7 @@ export interface BotProfile {
|
|
|
156
184
|
readonly managed?: boolean;
|
|
157
185
|
readonly agentConversationId?: string;
|
|
158
186
|
readonly proactivity?: 'inherit' | 'quiet' | 'low' | 'standard' | 'high' | 'muted';
|
|
187
|
+
readonly communicationStyle?: BotProfileCommunicationStyle;
|
|
159
188
|
/** Absent means this bot uses memory. */
|
|
160
189
|
readonly memoryEnabled?: boolean;
|
|
161
190
|
readonly planApproval?: 'never' | 'writes' | 'always';
|
|
@@ -177,6 +206,8 @@ export interface BotProfile {
|
|
|
177
206
|
readonly removePending: boolean;
|
|
178
207
|
} | null;
|
|
179
208
|
readonly modelPolicy?: ProjectModelPolicy | null;
|
|
209
|
+
/** Bot-mounted Skills & MCP overrides inherited by all derived child tasks. */
|
|
210
|
+
readonly capabilityPolicy?: BotCapabilityPolicy | null;
|
|
180
211
|
readonly updatedAt?: string;
|
|
181
212
|
}
|
|
182
213
|
export interface BotRowState {
|
|
@@ -193,6 +224,9 @@ export interface BotListItem {
|
|
|
193
224
|
readonly preview: string;
|
|
194
225
|
readonly lastActiveAt: string;
|
|
195
226
|
readonly state: BotRowState;
|
|
227
|
+
readonly activeSessions?: readonly BotListSession[];
|
|
228
|
+
readonly activeSessionTotal?: number;
|
|
229
|
+
readonly historySessionTotal?: number;
|
|
196
230
|
}
|
|
197
231
|
export interface BotListFilter {
|
|
198
232
|
readonly query?: string;
|
|
@@ -268,8 +302,18 @@ export type ProjectAgentStopResponseResult = {
|
|
|
268
302
|
readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'HOST_OFFLINE' | 'STALE_TURN' | 'INVALID_INPUT';
|
|
269
303
|
};
|
|
270
304
|
export interface BotListSession {
|
|
305
|
+
readonly sessionId?: string;
|
|
306
|
+
readonly title?: string;
|
|
271
307
|
readonly status: WorkSessionStatus;
|
|
272
308
|
readonly updatedAt?: string;
|
|
309
|
+
readonly followUp?: FollowUpProjection;
|
|
310
|
+
readonly phaseLabel?: string;
|
|
311
|
+
readonly anchorMessageId?: string;
|
|
312
|
+
readonly planId?: string;
|
|
313
|
+
readonly conversationId?: string;
|
|
314
|
+
readonly queueReason?: string;
|
|
315
|
+
readonly resultConfirmationRequired?: boolean;
|
|
316
|
+
readonly completionReviewRequired?: boolean;
|
|
273
317
|
}
|
|
274
318
|
export interface BotListApproval {
|
|
275
319
|
readonly state: PendingApprovalState;
|
|
@@ -298,3 +342,9 @@ export declare function projectBotListItem(input: {
|
|
|
298
342
|
}): BotListItem;
|
|
299
343
|
export declare function sortBotList(items: readonly BotListItem[]): BotListItem[];
|
|
300
344
|
export declare function filterBotList(items: readonly BotListItem[], filter?: BotListFilter): BotListItem[];
|
|
345
|
+
export declare function normalizeBotCapabilityPolicy(policy: BotCapabilityPolicy | null | undefined): BotCapabilityPolicy | null;
|
|
346
|
+
export declare function hasBotCapabilityOverrides(policy: BotCapabilityPolicy | null | undefined): boolean;
|
|
347
|
+
export declare function resolveBotSkillEnabled(policy: BotCapabilityPolicy | null | undefined, skillId: string, defaultEnabled: boolean): boolean;
|
|
348
|
+
export declare function resolveBotMcpEnabled(policy: BotCapabilityPolicy | null | undefined, mcpId: string, defaultEnabled: boolean): boolean;
|
|
349
|
+
export declare function toggleBotSkillOverride(policy: BotCapabilityPolicy | null | undefined, skillId: string, defaultEnabled: boolean, nextEnabled: boolean): BotCapabilityPolicy | null;
|
|
350
|
+
export declare function toggleBotMcpOverride(policy: BotCapabilityPolicy | null | undefined, mcpId: string, defaultEnabled: boolean, nextEnabled: boolean): BotCapabilityPolicy | null;
|
package/dist/project.js
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
* Bot list projection. Sort is recent activity only.
|
|
3
3
|
* needsYou changes the badge and the filter, not the order.
|
|
4
4
|
*/
|
|
5
|
+
export const BOT_AVATAR_HEADS = [
|
|
6
|
+
'none',
|
|
7
|
+
'beret',
|
|
8
|
+
'glasses',
|
|
9
|
+
'beanie',
|
|
10
|
+
'vermeer',
|
|
11
|
+
'straw',
|
|
12
|
+
'headphones',
|
|
13
|
+
'crown',
|
|
14
|
+
];
|
|
15
|
+
export const BOT_AVATAR_NECKS = [
|
|
16
|
+
'bowtie',
|
|
17
|
+
'scarf',
|
|
18
|
+
'sweater',
|
|
19
|
+
'moon',
|
|
20
|
+
'sailor',
|
|
21
|
+
'cape',
|
|
22
|
+
];
|
|
5
23
|
/** Display contract version for persisted agent_turn records (ADR87 D4).
|
|
6
24
|
* Version 2: public text carries role, the canonical agent_reply is the only
|
|
7
25
|
* answer body, and the implicit pure-text fallback reply is closed. Absent
|
|
@@ -107,3 +125,98 @@ export function filterBotList(items, filter = {}) {
|
|
|
107
125
|
return haystack.includes(query);
|
|
108
126
|
});
|
|
109
127
|
}
|
|
128
|
+
function dedupCapabilityIds(ids) {
|
|
129
|
+
if (!Array.isArray(ids))
|
|
130
|
+
return [];
|
|
131
|
+
const out = [];
|
|
132
|
+
const seen = new Set();
|
|
133
|
+
for (const raw of ids) {
|
|
134
|
+
if (typeof raw !== 'string')
|
|
135
|
+
continue;
|
|
136
|
+
const trimmed = raw.trim();
|
|
137
|
+
if (!trimmed || seen.has(trimmed))
|
|
138
|
+
continue;
|
|
139
|
+
seen.add(trimmed);
|
|
140
|
+
out.push(trimmed);
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
export function normalizeBotCapabilityPolicy(policy) {
|
|
145
|
+
if (!policy || typeof policy !== 'object')
|
|
146
|
+
return null;
|
|
147
|
+
const disabledSkillIds = dedupCapabilityIds(policy.disabledSkillIds);
|
|
148
|
+
const disabledSkillSet = new Set(disabledSkillIds);
|
|
149
|
+
const enabledSkillIds = dedupCapabilityIds(policy.enabledSkillIds).filter((id) => !disabledSkillSet.has(id));
|
|
150
|
+
const disabledMcpIds = dedupCapabilityIds(policy.disabledMcpIds);
|
|
151
|
+
const disabledMcpSet = new Set(disabledMcpIds);
|
|
152
|
+
const enabledMcpIds = dedupCapabilityIds(policy.enabledMcpIds).filter((id) => !disabledMcpSet.has(id));
|
|
153
|
+
if (enabledSkillIds.length === 0
|
|
154
|
+
&& disabledSkillIds.length === 0
|
|
155
|
+
&& enabledMcpIds.length === 0
|
|
156
|
+
&& disabledMcpIds.length === 0) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
...(enabledSkillIds.length > 0 ? { enabledSkillIds } : {}),
|
|
161
|
+
...(disabledSkillIds.length > 0 ? { disabledSkillIds } : {}),
|
|
162
|
+
...(enabledMcpIds.length > 0 ? { enabledMcpIds } : {}),
|
|
163
|
+
...(disabledMcpIds.length > 0 ? { disabledMcpIds } : {}),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
export function hasBotCapabilityOverrides(policy) {
|
|
167
|
+
return normalizeBotCapabilityPolicy(policy) !== null;
|
|
168
|
+
}
|
|
169
|
+
export function resolveBotSkillEnabled(policy, skillId, defaultEnabled) {
|
|
170
|
+
if (!policy)
|
|
171
|
+
return defaultEnabled;
|
|
172
|
+
if (policy.disabledSkillIds?.includes(skillId))
|
|
173
|
+
return false;
|
|
174
|
+
if (policy.enabledSkillIds?.includes(skillId))
|
|
175
|
+
return true;
|
|
176
|
+
return defaultEnabled;
|
|
177
|
+
}
|
|
178
|
+
export function resolveBotMcpEnabled(policy, mcpId, defaultEnabled) {
|
|
179
|
+
if (!policy)
|
|
180
|
+
return defaultEnabled;
|
|
181
|
+
if (policy.disabledMcpIds?.includes(mcpId))
|
|
182
|
+
return false;
|
|
183
|
+
if (policy.enabledMcpIds?.includes(mcpId))
|
|
184
|
+
return true;
|
|
185
|
+
return defaultEnabled;
|
|
186
|
+
}
|
|
187
|
+
export function toggleBotSkillOverride(policy, skillId, defaultEnabled, nextEnabled) {
|
|
188
|
+
const id = skillId.trim();
|
|
189
|
+
if (!id)
|
|
190
|
+
return normalizeBotCapabilityPolicy(policy);
|
|
191
|
+
const enabledSkillIds = dedupCapabilityIds(policy?.enabledSkillIds).filter((item) => item !== id);
|
|
192
|
+
const disabledSkillIds = dedupCapabilityIds(policy?.disabledSkillIds).filter((item) => item !== id);
|
|
193
|
+
if (nextEnabled !== defaultEnabled) {
|
|
194
|
+
if (nextEnabled)
|
|
195
|
+
enabledSkillIds.push(id);
|
|
196
|
+
else
|
|
197
|
+
disabledSkillIds.push(id);
|
|
198
|
+
}
|
|
199
|
+
return normalizeBotCapabilityPolicy({
|
|
200
|
+
...policy,
|
|
201
|
+
enabledSkillIds,
|
|
202
|
+
disabledSkillIds,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
export function toggleBotMcpOverride(policy, mcpId, defaultEnabled, nextEnabled) {
|
|
206
|
+
const id = mcpId.trim();
|
|
207
|
+
if (!id)
|
|
208
|
+
return normalizeBotCapabilityPolicy(policy);
|
|
209
|
+
const enabledMcpIds = dedupCapabilityIds(policy?.enabledMcpIds).filter((item) => item !== id);
|
|
210
|
+
const disabledMcpIds = dedupCapabilityIds(policy?.disabledMcpIds).filter((item) => item !== id);
|
|
211
|
+
if (nextEnabled !== defaultEnabled) {
|
|
212
|
+
if (nextEnabled)
|
|
213
|
+
enabledMcpIds.push(id);
|
|
214
|
+
else
|
|
215
|
+
disabledMcpIds.push(id);
|
|
216
|
+
}
|
|
217
|
+
return normalizeBotCapabilityPolicy({
|
|
218
|
+
...policy,
|
|
219
|
+
enabledMcpIds,
|
|
220
|
+
disabledMcpIds,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
@@ -7,7 +7,7 @@ const ownerships = new Set(['live', 'ended', 'unknown']);
|
|
|
7
7
|
const owners = new Set(['bot', 'user', 'none']);
|
|
8
8
|
const reasons = new Set(['settled', 'superseded', 'stop_confirmed', 'user_withdrawn',
|
|
9
9
|
'stop_unconfirmed', 'human_request', 'awaiting_human_gate', 'technical_block', 'local_persistence_failed', 'awaiting_acceptance_technical',
|
|
10
|
-
'verification_failed', 'live_execution', 'paused', 'unknown_facts', 'obligation_indexed']);
|
|
10
|
+
'verification_failed', 'execution_failed', 'live_execution', 'paused', 'unknown_facts', 'obligation_indexed']);
|
|
11
11
|
const hostReasons = new Set(['live_execution', 'stop_unconfirmed', 'unknown_facts', 'local_persistence_failed']);
|
|
12
12
|
export function runtimeSessionFacts(value) {
|
|
13
13
|
const row = record(value), origin = record(row.origin), cancellation = record(origin.cancellation);
|
|
@@ -36,7 +36,9 @@ export function runtimeSessionFacts(value) {
|
|
|
36
36
|
: executionOwnership === 'live' || stopping || owner === 'bot' && hostReasons.has(reason) ? 'host'
|
|
37
37
|
: owner === 'none' ? 'none' : 'model';
|
|
38
38
|
return { sessionId, status, valid, executionOwnership, owner, reason, handling,
|
|
39
|
-
pendingManaged: reason === 'obligation_indexed'
|
|
39
|
+
pendingManaged: reason === 'obligation_indexed' || (reason === 'execution_failed' && handling === 'none')
|
|
40
|
+
? false
|
|
41
|
+
: handling === 'host' || handling === 'user' || !['accepted', 'cancelled'].includes(status) };
|
|
40
42
|
}
|
|
41
43
|
/** Missing/invalid facts remain obligations; a valid public terminal does not invent live ownership. */
|
|
42
44
|
export function hasPendingRuntimeSessions(sessions, expectedIds = []) {
|
|
@@ -163,6 +163,17 @@ export interface UnknownOutcomeResolution {
|
|
|
163
163
|
readonly unknownCalls: readonly string[];
|
|
164
164
|
readonly at: string;
|
|
165
165
|
}
|
|
166
|
+
/** ADR 131: local transport ownership only; never proof of remote tool effects. */
|
|
167
|
+
export interface NativeMcpHandleObservation {
|
|
168
|
+
readonly schemaVersion: 1;
|
|
169
|
+
readonly role: 'rpc' | 'connection';
|
|
170
|
+
readonly transport: 'stdio' | 'streamable_http' | 'sse';
|
|
171
|
+
readonly registryRevision: string;
|
|
172
|
+
readonly ownerRecorder: NonNullable<SessionControlOperation['recorder']>;
|
|
173
|
+
readonly childRecorder?: NonNullable<SessionControlOperation['recorder']>;
|
|
174
|
+
readonly ownerStopObservation?: 'original_owner_dead';
|
|
175
|
+
readonly childStopObservation?: 'group_absent';
|
|
176
|
+
}
|
|
166
177
|
export interface ExecutionResourceClaim {
|
|
167
178
|
readonly claimId: string;
|
|
168
179
|
readonly resourceRef: string;
|
|
@@ -176,6 +187,7 @@ export interface ExecutionResourceClaim {
|
|
|
176
187
|
readonly toolCallId: string;
|
|
177
188
|
readonly state: 'active' | 'ended' | 'unknown';
|
|
178
189
|
readonly completedAt?: string;
|
|
190
|
+
readonly nativeMcp?: NativeMcpHandleObservation;
|
|
179
191
|
}>>;
|
|
180
192
|
readonly evidenceCalls: readonly string[];
|
|
181
193
|
/** Absent means the legacy directory scope derived from resourceRef; dispatch-declared scopes arrive with claim scope convergence. */
|
package/dist/task-overview.d.ts
CHANGED
|
@@ -407,6 +407,7 @@ export interface LifecycleFacts {
|
|
|
407
407
|
readonly interrupted?: boolean;
|
|
408
408
|
readonly interruptionOrigin?: import('./agent-supervision.ts').InterruptionOrigin;
|
|
409
409
|
readonly verificationActive?: boolean;
|
|
410
|
+
readonly verificationFailed?: boolean;
|
|
410
411
|
readonly blockedReason?: string;
|
|
411
412
|
readonly cancellationPhase?: string;
|
|
412
413
|
readonly cancellationDisposition?: 'user_withdrawn';
|
|
@@ -427,7 +428,7 @@ export interface LifecycleCoreDecision extends ProjectionDecision {
|
|
|
427
428
|
* `inCurrentList` 是派生事实,不允许消费端各自按 status 再判一次。
|
|
428
429
|
*/
|
|
429
430
|
export type FollowUpOwner = 'bot' | 'user' | 'none';
|
|
430
|
-
export type FollowUpReason = 'settled' | 'superseded' | 'stop_confirmed' | 'user_withdrawn' | 'stop_unconfirmed' | 'human_request' | 'awaiting_human_gate' | 'technical_block' | 'local_persistence_failed' | 'awaiting_acceptance_technical' | 'verification_failed' | 'live_execution' | 'paused' | 'unknown_facts' | 'obligation_indexed';
|
|
431
|
+
export type FollowUpReason = 'settled' | 'superseded' | 'stop_confirmed' | 'user_withdrawn' | 'stop_unconfirmed' | 'human_request' | 'awaiting_human_gate' | 'technical_block' | 'local_persistence_failed' | 'awaiting_acceptance_technical' | 'verification_failed' | 'execution_failed' | 'live_execution' | 'paused' | 'unknown_facts' | 'obligation_indexed';
|
|
431
432
|
export interface FollowUpProjection {
|
|
432
433
|
readonly owner: FollowUpOwner;
|
|
433
434
|
readonly inCurrentList: boolean;
|
package/dist/task-overview.js
CHANGED
|
@@ -39,8 +39,11 @@ export function decideFollowUp(decision, facts = {}, ownership = 'unknown') {
|
|
|
39
39
|
// 3) 核验失败/缺证据:即使存在历史 accepted 事实也不能静默(那次验收是旧结论)。
|
|
40
40
|
if (['failed', 'waiting_agent'].includes(status) && facts.blockedReason === 'conversation_persistence_failed')
|
|
41
41
|
return followUpOf('bot', 'local_persistence_failed');
|
|
42
|
-
if (status === '
|
|
42
|
+
if (status === 'result_ready' && facts.verificationFailed === true)
|
|
43
43
|
return followUpOf('bot', 'verification_failed');
|
|
44
|
+
// 终态执行失败(未产生可核验结果):归入历史记录,不再伪装成待重验任务钉死在活跃列表。
|
|
45
|
+
if (status === 'failed')
|
|
46
|
+
return followUpOf('none', 'execution_failed');
|
|
44
47
|
if (facts.accepted === true)
|
|
45
48
|
return followUpOf('none', 'settled');
|
|
46
49
|
if (stopStatus)
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Usage scopes are deliberately explicit because the same token fields have
|
|
3
3
|
* different meanings at each runtime boundary.
|
|
4
4
|
*/
|
|
5
|
+
import type { SessionExecutionIdentity } from './session-control.ts';
|
|
5
6
|
export type UsageScope = 'provider_request' | 'runtime_turn' | 'conversation_lifetime';
|
|
6
7
|
export interface UsageAmounts {
|
|
7
8
|
readonly inputTokens: number;
|
|
@@ -22,6 +23,34 @@ export interface RuntimeTurnUsage extends UsageAmounts {
|
|
|
22
23
|
readonly usageScope: 'runtime_turn';
|
|
23
24
|
readonly providerRequestCount: number;
|
|
24
25
|
}
|
|
26
|
+
/** ADR131 canonical billing snapshot. It never seeds context or proves execution. */
|
|
27
|
+
export interface NativeRuntimeUsageSnapshot {
|
|
28
|
+
readonly schemaVersion: 1;
|
|
29
|
+
readonly knownAmountsOnly: true;
|
|
30
|
+
readonly workId: string;
|
|
31
|
+
readonly execution: SessionExecutionIdentity;
|
|
32
|
+
readonly conversationId: string;
|
|
33
|
+
readonly usage: RuntimeTurnUsage;
|
|
34
|
+
readonly attribution: {
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly streamId: string;
|
|
37
|
+
readonly at: string;
|
|
38
|
+
readonly modelProviderId: string;
|
|
39
|
+
readonly model: string;
|
|
40
|
+
readonly groupId?: string | null;
|
|
41
|
+
readonly role: 'work_session';
|
|
42
|
+
readonly workspaceId: string;
|
|
43
|
+
readonly providerName?: string | null;
|
|
44
|
+
readonly estimatedCostUsd?: number | null;
|
|
45
|
+
readonly pricingSource?: string | null;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** One bounded native recovery batch; remaining records retain their identity. */
|
|
49
|
+
export interface NativeUsageRecoveryProgress {
|
|
50
|
+
readonly schemaVersion: 1;
|
|
51
|
+
readonly settled: number;
|
|
52
|
+
readonly remaining: number;
|
|
53
|
+
}
|
|
25
54
|
/** Durable billable sum for one provider/model key inside a conversation ledger. */
|
|
26
55
|
export interface ConversationLifetimeModelUsage {
|
|
27
56
|
/** Stable provider binding id, e.g. '5198c365-...::ultimate'. */
|
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import type { ProjectRecoveryFailureKind } from './project-agent-failure.ts';
|
|
2
|
+
import type { SessionExecutionIdentity, SessionControlOperation } from './session-control.ts';
|
|
3
|
+
import type { NativeOwnedProcess } from './native-process.ts';
|
|
4
|
+
/** ADR 131 native attempt metadata. Shape alone proves neither death nor effect. */
|
|
5
|
+
export interface NativeEpisodeRecorder {
|
|
6
|
+
readonly schemaVersion: 1;
|
|
7
|
+
readonly runtime: 'peer-native';
|
|
8
|
+
readonly execution: SessionExecutionIdentity;
|
|
9
|
+
readonly recorder: NonNullable<SessionControlOperation['recorder']>;
|
|
10
|
+
}
|
|
2
11
|
export interface ProjectWorkBudgetLimits {
|
|
3
12
|
readonly schemaVersion?: 2;
|
|
4
13
|
readonly source: string;
|
|
@@ -144,13 +153,25 @@ export interface ProjectWorkReceipt {
|
|
|
144
153
|
readonly requests?: number;
|
|
145
154
|
readonly modelProviderId?: string;
|
|
146
155
|
readonly checkpointRef?: string;
|
|
156
|
+
readonly nativeRecorder?: NativeEpisodeRecorder;
|
|
157
|
+
/** Unvalidated stored snapshot; admit v1 before consuming billing facts. */
|
|
158
|
+
readonly nativeUsage?: unknown;
|
|
159
|
+
/** Loop admission ended; this is not a stop receipt. */
|
|
160
|
+
readonly nativeLoopFinished?: true;
|
|
147
161
|
readonly pendingTools?: readonly {
|
|
148
162
|
readonly toolCallId: string | null;
|
|
149
163
|
readonly capabilityId: string | null;
|
|
150
164
|
readonly verificationSessionId?: string;
|
|
165
|
+
readonly nativeRecorder?: NativeEpisodeRecorder;
|
|
166
|
+
readonly nativeProcess?: NativeOwnedProcess;
|
|
151
167
|
}[];
|
|
152
168
|
}>>;
|
|
153
169
|
readonly reconciledDispatches?: readonly VerificationDispatchReconciliation[];
|
|
170
|
+
/** Keep unknown/future records intact until a compatible billing owner acts. */
|
|
171
|
+
readonly nativeUsagePending?: Readonly<Record<string, {
|
|
172
|
+
readonly snapshot: unknown;
|
|
173
|
+
readonly nativeRecorder: unknown;
|
|
174
|
+
}>>;
|
|
154
175
|
readonly settledDispatches?: readonly SettledDelegationDispatch[];
|
|
155
176
|
readonly uncertainDispatches?: readonly {
|
|
156
177
|
readonly attemptId: string;
|
|
@@ -158,6 +179,8 @@ export interface ProjectWorkReceipt {
|
|
|
158
179
|
readonly toolCallId: string | null;
|
|
159
180
|
readonly capabilityId: string | null;
|
|
160
181
|
readonly verificationSessionId?: string;
|
|
182
|
+
readonly nativeRecorder?: NativeEpisodeRecorder;
|
|
183
|
+
readonly nativeProcess?: NativeOwnedProcess;
|
|
161
184
|
}[];
|
|
162
185
|
};
|
|
163
186
|
readonly stopScope: 'reply' | 'work';
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { isHookObservation } from "./hook-observation.js";
|
|
2
|
+
import { nativeProcessEnvelopeValid } from "./native-process.js";
|
|
3
|
+
import { normalizeSessionExecutionIdentity } from "./session-control.js";
|
|
4
|
+
export const WORK_HOOK_SEMANTIC_FLOOR = 14;
|
|
5
|
+
const maxHandles = 256;
|
|
6
|
+
const invalid = () => { throw new Error('native_work_hooks_invalid'); };
|
|
7
|
+
const record = (input) => input !== null && typeof input === 'object' && !Array.isArray(input) ? input : undefined;
|
|
8
|
+
const requiredId = (input) => typeof input === 'string' && input.length > 0
|
|
9
|
+
&& new TextEncoder().encode(input).length <= 200;
|
|
10
|
+
const ownerKeys = ['pid', 'pidStart', 'bootId', 'hostId', 'acquiredAt'];
|
|
11
|
+
/** Shape only. OS observation, ownership and business effects require Host evidence. */
|
|
12
|
+
export function nativeWorkHasHookFacts(work) {
|
|
13
|
+
const budget = record(record(work)?.budget);
|
|
14
|
+
const pending = Object.values(record(budget?.attempts) ?? {}).flatMap(attempt => {
|
|
15
|
+
const pending = record(attempt)?.pendingTools;
|
|
16
|
+
return Array.isArray(pending) ? pending : [];
|
|
17
|
+
});
|
|
18
|
+
const rows = pending.concat(Array.isArray(budget?.uncertainDispatches) ? budget.uncertainDispatches : []);
|
|
19
|
+
const ids = new Set();
|
|
20
|
+
let found = false;
|
|
21
|
+
for (const input of rows) {
|
|
22
|
+
const row = record(input);
|
|
23
|
+
if (!row || !Object.hasOwn(row, 'nativeHooks'))
|
|
24
|
+
continue;
|
|
25
|
+
const hooks = record(row.nativeHooks);
|
|
26
|
+
const recorder = record(row.nativeRecorder);
|
|
27
|
+
const owner = record(recorder?.recorder);
|
|
28
|
+
const execution = normalizeSessionExecutionIdentity(recorder?.execution);
|
|
29
|
+
const provider = record(row.nativeProcess);
|
|
30
|
+
const intent = record(hooks?.intent);
|
|
31
|
+
if (!hooks || Object.keys(hooks).some(key => !['schemaVersion', 'providerPhase', 'handles', 'intent', 'grant'].includes(key))
|
|
32
|
+
|| Object.hasOwn(hooks, 'intent') && (!intent || Object.keys(intent).length !== 2
|
|
33
|
+
|| !requiredId(intent.messageId) || /[\u0000-\u001f\u007f-\u009f]/u.test(intent.messageId)
|
|
34
|
+
|| typeof intent.argsDigest !== 'string' || !/^[a-f0-9]{64}$/.test(intent.argsDigest))
|
|
35
|
+
|| hooks.schemaVersion !== 1
|
|
36
|
+
|| !['prepared', 'dispatching'].some(phase => phase === hooks.providerPhase)
|
|
37
|
+
|| !Array.isArray(hooks.handles) || hooks.handles.length > maxHandles
|
|
38
|
+
|| recorder?.schemaVersion !== 1 || recorder.runtime !== 'peer-native' || !owner || !execution
|
|
39
|
+
|| !Number.isInteger(owner.pid) || owner.pid <= 0 || owner.pid > 2147483647
|
|
40
|
+
|| ownerKeys.slice(1).some(key => typeof owner[key] !== 'string' || !owner[key].length
|
|
41
|
+
|| new TextEncoder().encode(owner[key]).length > 8192)
|
|
42
|
+
|| !requiredId(row.toolCallId) || !requiredId(row.dispatchId)
|
|
43
|
+
|| hooks.providerPhase === 'prepared' && Object.hasOwn(row, 'nativeProcess'))
|
|
44
|
+
return invalid();
|
|
45
|
+
if (Object.hasOwn(hooks, 'grant')) {
|
|
46
|
+
const grant = record(hooks.grant);
|
|
47
|
+
if (hooks.providerPhase !== 'dispatching' || !intent || !grant || grant.granted !== true
|
|
48
|
+
|| grant.toolCallId !== row.toolCallId || grant.duration !== 'once'
|
|
49
|
+
|| typeof grant.grantId !== 'string' || grant.grantId.length === 0)
|
|
50
|
+
return invalid();
|
|
51
|
+
}
|
|
52
|
+
found = true;
|
|
53
|
+
for (const input of hooks.handles) {
|
|
54
|
+
const hook = record(input);
|
|
55
|
+
const process = record(hook?.process);
|
|
56
|
+
const processOwner = record(process?.owner);
|
|
57
|
+
const processExecution = normalizeSessionExecutionIdentity(process?.execution);
|
|
58
|
+
if (!hook || Object.keys(hook).some(key => !['event', 'ruleDigest', 'process', 'observation'].includes(key))
|
|
59
|
+
|| !['PreToolUse', 'PostToolUse'].some(event => event === hook.event)
|
|
60
|
+
|| hooks.providerPhase === 'prepared' && hook.event === 'PostToolUse'
|
|
61
|
+
|| typeof hook.ruleDigest !== 'string' || !/^[a-f0-9]{64}$/.test(hook.ruleDigest)
|
|
62
|
+
|| !process || !nativeProcessEnvelopeValid(process) || !processOwner || !processExecution
|
|
63
|
+
|| ownerKeys.some(key => processOwner[key] !== owner[key])
|
|
64
|
+
|| JSON.stringify(processExecution) !== JSON.stringify(execution)
|
|
65
|
+
|| process.toolCallId !== row.toolCallId || process.dispatchId !== row.dispatchId
|
|
66
|
+
|| process.generation > 1
|
|
67
|
+
|| ids.size >= maxHandles || ids.has(process.handleId) || process.handleId === provider?.handleId
|
|
68
|
+
|| (process.stopObservation === 'owned_completion'
|
|
69
|
+
? !isHookObservation(hook.observation, hook.event, hook.ruleDigest, process.handleId)
|
|
70
|
+
: Object.hasOwn(hook, 'observation')))
|
|
71
|
+
return invalid();
|
|
72
|
+
ids.add(process.handleId);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return found;
|
|
76
|
+
}
|