@mogragsigma/dsh-dual-host-plugin 0.0.0-stage → 0.33.2
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/LICENSE +58 -0
- package/LICENSE.en.md +94 -0
- package/README.md +88 -2
- package/bundle/ASSET_NOTICE.md +19 -0
- package/bundle/LICENSE +58 -0
- package/bundle/LICENSE.en.md +94 -0
- package/bundle/README.md +75 -0
- package/bundle/THIRD_PARTY_NOTICES.md +94 -0
- package/bundle/a2a-dispatches.js +38 -0
- package/bundle/a2a-endpoint.js +112 -0
- package/bundle/a2a-tools.js +11 -0
- package/bundle/a2a-worker.js +63 -0
- package/bundle/approval-auth.js +5 -0
- package/bundle/approval-chat.js +150 -0
- package/bundle/approval-feishu.js +52 -0
- package/bundle/approval-guidance.js +68 -0
- package/bundle/approval-http.js +8 -0
- package/bundle/approval-ledger.js +142 -0
- package/bundle/approval-local-relay.js +86 -0
- package/bundle/approval-receipts.js +62 -0
- package/bundle/approval-reference.js +33 -0
- package/bundle/approval-semantic-model.js +26 -0
- package/bundle/approval-semantics.js +51 -0
- package/bundle/approval-ui/app.js +1 -0
- package/bundle/approval-ui/index.html +1 -0
- package/bundle/approval-ui/style.css +1 -0
- package/bundle/approval-workbench.js +45 -0
- package/bundle/artifact-media.js +34 -0
- package/bundle/bounded-text.js +44 -0
- package/bundle/compatibility.json +980 -0
- package/bundle/cordis.patch.yml +5 -0
- package/bundle/delivery-approval.js +133 -0
- package/bundle/delivery-artifacts.js +52 -0
- package/bundle/delivery-commit.js +125 -0
- package/bundle/delivery-contract.js +42 -0
- package/bundle/delivery-git-read.js +217 -0
- package/bundle/delivery-index.js +23 -0
- package/bundle/delivery-journal.js +207 -0
- package/bundle/delivery-object-plan.js +138 -0
- package/bundle/delivery-preview.js +153 -0
- package/bundle/delivery-process-receipts.js +90 -0
- package/bundle/delivery-process.js +46 -0
- package/bundle/delivery-process.py +228 -0
- package/bundle/delivery-push-approval.js +89 -0
- package/bundle/delivery-push-plan.js +98 -0
- package/bundle/delivery-push-recovery.js +32 -0
- package/bundle/delivery-push.js +83 -0
- package/bundle/delivery-recovery.js +143 -0
- package/bundle/delivery-runtime.js +182 -0
- package/bundle/delivery-ssh.js +64 -0
- package/bundle/delivery-state.js +106 -0
- package/bundle/development-attention.js +35 -0
- package/bundle/development-bridge.js +136 -0
- package/bundle/development-command-review.js +110 -0
- package/bundle/development-container.js +110 -0
- package/bundle/development-contract.js +17 -0
- package/bundle/development-files.js +101 -0
- package/bundle/development-gate.js +236 -0
- package/bundle/development-model-budget.js +48 -0
- package/bundle/development-peer.js +155 -0
- package/bundle/development-plan.js +43 -0
- package/bundle/development-reconciliation.js +62 -0
- package/bundle/development-review.js +81 -0
- package/bundle/development-rules/AGENTS.md +51 -0
- package/bundle/development-runtime.js +68 -0
- package/bundle/development-source.js +48 -0
- package/bundle/development-test-runner.js +13 -0
- package/bundle/development-tools.js +45 -0
- package/bundle/development-worker-review.js +110 -0
- package/bundle/development-worker.js +68 -0
- package/bundle/development-workspace.js +54 -0
- package/bundle/diagnostics.js +78 -0
- package/bundle/distribution-lock.json +773 -0
- package/bundle/drained-process.js +26 -0
- package/bundle/durable-inbox.js +294 -0
- package/bundle/feishu-policy.js +24 -0
- package/bundle/gateway-maintenance.js +55 -0
- package/bundle/global-rules/AGENTS.md +83 -0
- package/bundle/im-delivery.js +60 -0
- package/bundle/index.js +445 -0
- package/bundle/intervention-actions.js +135 -0
- package/bundle/intervention-job-control.js +28 -0
- package/bundle/intervention-state.js +43 -0
- package/bundle/job-version.js +15 -0
- package/bundle/legacy-feishu-adapter.js +89 -0
- package/bundle/link-contract.js +80 -0
- package/bundle/maintenance-process-identity.js +93 -0
- package/bundle/model-selection.js +71 -0
- package/bundle/native-context.js +14 -0
- package/bundle/native-entry-admission.js +2 -0
- package/bundle/native-entry.js +58 -0
- package/bundle/native-file-reference.js +32 -0
- package/bundle/native-owner-origin.js +12 -0
- package/bundle/native-rules/AGENTS.md +199 -0
- package/bundle/native-tools.js +108 -0
- package/bundle/notification-artifacts.js +70 -0
- package/bundle/notification-contract.js +29 -0
- package/bundle/notification-defaults.js +81 -0
- package/bundle/notification-discovery.js +65 -0
- package/bundle/notification-endpoint.js +54 -0
- package/bundle/notification-feishu.js +51 -0
- package/bundle/notification-media-endpoint.js +94 -0
- package/bundle/notification-review.js +27 -0
- package/bundle/notification-targets.js +54 -0
- package/bundle/onboarding-activity.js +66 -0
- package/bundle/onboarding-agent-hold.js +94 -0
- package/bundle/onboarding-boundary.js +20 -0
- package/bundle/onboarding-cloud-contract.js +29 -0
- package/bundle/onboarding-cloud-file-review.js +58 -0
- package/bundle/onboarding-cloud-files.js +100 -0
- package/bundle/onboarding-cloud-im.js +34 -0
- package/bundle/onboarding-cloud-model-probe.js +53 -0
- package/bundle/onboarding-cloud-models.js +68 -0
- package/bundle/onboarding-cloud-operation.js +276 -0
- package/bundle/onboarding-cloud-package.js +38 -0
- package/bundle/onboarding-cloud-repositories.js +89 -0
- package/bundle/onboarding-cloud-retirement.js +59 -0
- package/bundle/onboarding-cloud-task-runtime.js +90 -0
- package/bundle/onboarding-cloud-web.js +85 -0
- package/bundle/onboarding-cloud.js +110 -0
- package/bundle/onboarding-coordinated-hold.js +94 -0
- package/bundle/onboarding-exclusive-rename.js +16 -0
- package/bundle/onboarding-existing-host.js +63 -0
- package/bundle/onboarding-existing-setup.js +123 -0
- package/bundle/onboarding-file-contract.js +31 -0
- package/bundle/onboarding-file-review-contract.js +38 -0
- package/bundle/onboarding-file-transfer.js +133 -0
- package/bundle/onboarding-handoff-remote.js +98 -0
- package/bundle/onboarding-handoff.js +112 -0
- package/bundle/onboarding-host-stop-observation.js +44 -0
- package/bundle/onboarding-host.js +254 -0
- package/bundle/onboarding-identity.js +9 -0
- package/bundle/onboarding-im-maintenance-native.js +30 -0
- package/bundle/onboarding-im-maintenance.js +70 -0
- package/bundle/onboarding-im.js +31 -0
- package/bundle/onboarding-inspection-guard.js +15 -0
- package/bundle/onboarding-install-fs.js +58 -0
- package/bundle/onboarding-installer.js +157 -0
- package/bundle/onboarding-local-pair-native.js +21 -0
- package/bundle/onboarding-local-pair.js +99 -0
- package/bundle/onboarding-maintenance-fs.js +69 -0
- package/bundle/onboarding-maintenance-plan.js +213 -0
- package/bundle/onboarding-maintenance-record.js +169 -0
- package/bundle/onboarding-maintenance.js +163 -0
- package/bundle/onboarding-model-probe.js +119 -0
- package/bundle/onboarding-models.js +107 -0
- package/bundle/onboarding-native-host.js +101 -0
- package/bundle/onboarding-native-probe.js +56 -0
- package/bundle/onboarding-native-runner.js +29 -0
- package/bundle/onboarding-node-bootstrap.py +678 -0
- package/bundle/onboarding-node.js +77 -0
- package/bundle/onboarding-notification-defaults.js +93 -0
- package/bundle/onboarding-package-source.js +33 -0
- package/bundle/onboarding-paths.js +58 -0
- package/bundle/onboarding-peer-binding.js +61 -0
- package/bundle/onboarding-peer-contract.js +12 -0
- package/bundle/onboarding-plugin-repair.js +116 -0
- package/bundle/onboarding-plugin-version.js +143 -0
- package/bundle/onboarding-remote-control.js +140 -0
- package/bundle/onboarding-remote-probe.js +40 -0
- package/bundle/onboarding-repositories.js +88 -0
- package/bundle/onboarding-repository.js +49 -0
- package/bundle/onboarding-runtime-activation.js +83 -0
- package/bundle/onboarding-runtime-artifacts-client.js +87 -0
- package/bundle/onboarding-runtime-artifacts.js +126 -0
- package/bundle/onboarding-runtime-extension.js +400 -0
- package/bundle/onboarding-runtime-inventory.js +88 -0
- package/bundle/onboarding-runtime-program.js +42 -0
- package/bundle/onboarding-runtime-reclaim-client.js +94 -0
- package/bundle/onboarding-runtime-reclaim-worker.js +63 -0
- package/bundle/onboarding-runtime-reclaim.js +132 -0
- package/bundle/onboarding-runtime-repair-client.js +50 -0
- package/bundle/onboarding-runtime-repair.js +88 -0
- package/bundle/onboarding-runtime-stop.js +90 -0
- package/bundle/onboarding-runtime-uninstall-client.js +88 -0
- package/bundle/onboarding-runtime-uninstall.js +167 -0
- package/bundle/onboarding-runtime-version-client.js +138 -0
- package/bundle/onboarding-runtime-version.js +145 -0
- package/bundle/onboarding-schema.js +42 -0
- package/bundle/onboarding-self-disable.js +3 -0
- package/bundle/onboarding-self-lifecycle.js +95 -0
- package/bundle/onboarding-self-maintenance.js +52 -0
- package/bundle/onboarding-self-remove.js +3 -0
- package/bundle/onboarding-self-stop.js +85 -0
- package/bundle/onboarding-ssh-forward.js +48 -0
- package/bundle/onboarding-ssh.js +105 -0
- package/bundle/onboarding-state.js +95 -0
- package/bundle/onboarding-task-runtime-contract.js +38 -0
- package/bundle/onboarding-task-runtime-native.js +80 -0
- package/bundle/onboarding-task-runtime.js +66 -0
- package/bundle/onboarding-token-plan.js +52 -0
- package/bundle/onboarding-version-activation-client.js +48 -0
- package/bundle/onboarding-version-candidate.js +96 -0
- package/bundle/onboarding-version-repair.js +128 -0
- package/bundle/package-lock.json +773 -0
- package/bundle/package.json +99 -0
- package/bundle/peer-file-fs.js +62 -0
- package/bundle/peer-file-migration.js +59 -0
- package/bundle/peer-file-review.js +107 -0
- package/bundle/peer-files.js +157 -0
- package/bundle/peer-mailbox.js +75 -0
- package/bundle/protocol.js +17 -0
- package/bundle/recovery.js +40 -0
- package/bundle/repository-catalog.js +85 -0
- package/bundle/repository-gitee.js +76 -0
- package/bundle/repository-managed.js +46 -0
- package/bundle/repository-writer.js +43 -0
- package/bundle/rules/AGENTS.md +22 -0
- package/bundle/runtime-im-lock.json +11577 -0
- package/bundle/runtime-im-package.json +18 -0
- package/bundle/runtime-lock.json +10152 -0
- package/bundle/runtime-package.json +17 -0
- package/bundle/scheduler-migration.js +45 -0
- package/bundle/search-contract.js +19 -0
- package/bundle/skills/dsh-dual-end/SKILL.md +12 -0
- package/bundle/skills/task-a2a/SKILL.md +55 -0
- package/bundle/skills/task-a2a-worker/SKILL.md +23 -0
- package/bundle/skills/task-approval/SKILL.md +128 -0
- package/bundle/skills/task-artifacts/SKILL.md +46 -0
- package/bundle/skills/task-development/SKILL.md +144 -0
- package/bundle/skills/task-diagnostics/SKILL.md +41 -0
- package/bundle/skills/task-direct-link/SKILL.md +143 -0
- package/bundle/skills/task-file-transfer/SKILL.md +107 -0
- package/bundle/skills/task-handoff/SKILL.md +23 -0
- package/bundle/skills/task-intake/SKILL.md +13 -0
- package/bundle/skills/task-notify/SKILL.md +102 -0
- package/bundle/skills/task-onboarding/SKILL.md +708 -0
- package/bundle/skills/task-recovery/SKILL.md +54 -0
- package/bundle/skills/task-repository/SKILL.md +145 -0
- package/bundle/skills/task-research/SKILL.md +43 -0
- package/bundle/skills/task-schedule/SKILL.md +79 -0
- package/bundle/skills/task-sidebar/SKILL.md +122 -0
- package/bundle/skills/task-workbench/SKILL.md +30 -0
- package/bundle/skills/task-worker/SKILL.md +88 -0
- package/bundle/source-search.js +89 -0
- package/bundle/source-web.js +17 -0
- package/bundle/ssh-connector.js +24 -0
- package/bundle/store.js +102 -0
- package/bundle/task-a2a.js +298 -0
- package/bundle/task-artifacts.js +179 -0
- package/bundle/task-board-a2a.js +55 -0
- package/bundle/task-board-development.js +83 -0
- package/bundle/task-board-planning.js +84 -0
- package/bundle/task-board.js +132 -0
- package/bundle/task-branch.js +2 -0
- package/bundle/task-catalog.js +77 -0
- package/bundle/task-context.js +40 -0
- package/bundle/task-envelope.js +96 -0
- package/bundle/task-interventions.js +54 -0
- package/bundle/task-jobs.js +156 -0
- package/bundle/task-notifications.js +132 -0
- package/bundle/task-results.js +16 -0
- package/bundle/task-scheduler.js +77 -0
- package/bundle/task-sources.js +101 -0
- package/bundle/task-trigger-time.js +46 -0
- package/bundle/task-triggers.js +157 -0
- package/bundle/task-worker.js +73 -0
- package/bundle/task-workflows.js +117 -0
- package/bundle/tools.js +13 -0
- package/bundle/workbench-assets/asset-provenance.json +26 -0
- package/bundle/workbench-assets/whale-ui-states.png +0 -0
- package/bundle/workbench-client.js +811 -0
- package/bundle/workbench-decisions.js +48 -0
- package/bundle/workbench-host.js +122 -0
- package/bundle/workbench-im-identity.js +51 -0
- package/bundle/workbench-proxy.js +127 -0
- package/bundle/worker-rules/AGENTS.md +84 -0
- package/bundle/worker-tools.js +13 -0
- package/compatibility.json +980 -0
- package/cordis.patch.yml +3 -0
- package/package.json +57 -4
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {parseEnvelope} from './task-envelope.js';
|
|
3
|
+
import {isSearchJobVersion} from './job-version.js';
|
|
4
|
+
import {sourceUrl} from './source-web.js';
|
|
5
|
+
const sha=x=>createHash('sha256').update(x).digest('hex');
|
|
6
|
+
const base='https://api.deepseek.com/anthropic/v1';
|
|
7
|
+
const object=v=>!!v&&typeof v==='object'&&!Array.isArray(v);
|
|
8
|
+
// Public root exports only. The adapter's default model/settings/account route are never reused.
|
|
9
|
+
export async function createTaskSearchReader(ctx,config){
|
|
10
|
+
const [{DeepSeekSearchProvider},{credentialRef},{proxyRouteFor}]=await Promise.all([import('@deepseek-ai/dsh-web-search-deepseek'),import('@deepseek-ai/dsh-credentials'),import('@deepseek-ai/dsh-http-proxy')]);
|
|
11
|
+
const reference=credentialRef(config.credentialRef);
|
|
12
|
+
return {async search(query,policy,signal,recordRequest){
|
|
13
|
+
if(policy.provider!=='deepseek-official'||policy.reasoningEffort!=='disabled')throw Error('SOURCE_SEARCH_PROVIDER_UNSUPPORTED');
|
|
14
|
+
if(proxyRouteFor(new URL(base)).proxied||Object.entries(process.env).some(([k,v])=>/^(?:https?|all)_proxy$/i.test(k)&&v))throw Error('SOURCE_PROXY_UNSUPPORTED');
|
|
15
|
+
const credentials=ctx.get?.('credentials')??ctx.credentials;if(!credentials?.resolve)throw Error('SOURCE_SEARCH_CREDENTIAL_UNAVAILABLE');
|
|
16
|
+
const provider=new DeepSeekSearchProvider(()=>({baseURL:base,model:policy.model,apiVersion:'2023-06-01',maxTokens:2048,maxUses:1,
|
|
17
|
+
apiKeyEnv:reference,resolveApiKey:async()=>{signal.throwIfAborted();return (await credentials.resolve(reference))?.value;},recordRequest}));
|
|
18
|
+
return provider.search({query,maxResults:5},signal);
|
|
19
|
+
}};
|
|
20
|
+
}
|
|
21
|
+
export class TaskSearch {
|
|
22
|
+
constructor(sources,config,io={}){
|
|
23
|
+
this.s=sources;this.g=sources.g;this.db=sources.db;this.pending=new Map();this.state=config?'loading':'disabled';this.reader=null;
|
|
24
|
+
if(config&&(!object(config)||Object.keys(config).some(k=>k!=='credentialRef')||typeof config.credentialRef!=='string'||!/^[_a-zA-Z][_a-zA-Z0-9]*$/.test(config.credentialRef)))throw Error('SOURCE_SEARCH_CONFIG_INVALID');
|
|
25
|
+
this.db.exec('CREATE TABLE IF NOT EXISTS task_search_operations(event_id TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,run_id TEXT NOT NULL,state TEXT NOT NULL,error TEXT,request TEXT,created INTEGER NOT NULL);');
|
|
26
|
+
this.ready=config?(io.createSearchReader??createTaskSearchReader)(this.g.ctx,config).then(r=>{if(typeof r?.search!=='function')throw Error();this.reader=r;this.state='ready';}).catch(()=>{this.state='unavailable';}):Promise.resolve();
|
|
27
|
+
}
|
|
28
|
+
admit(job){
|
|
29
|
+
const e=parseEnvelope(job.goal);if(!e?.search)return;
|
|
30
|
+
if(!isSearchJobVersion(job.version))throw Error('SOURCE_SEARCH_VERSION_REQUIRED');
|
|
31
|
+
if(this.state!=='ready')throw Error('SOURCE_SEARCH_UNAVAILABLE');
|
|
32
|
+
if(e.search.model_policy.provider!=='deepseek-official')throw Error('SOURCE_SEARCH_PROVIDER_UNSUPPORTED');
|
|
33
|
+
if(this.uncertain(job))throw Error('SOURCE_SEARCH_DISPATCH_UNCERTAIN');
|
|
34
|
+
}
|
|
35
|
+
policy(worker,agent){
|
|
36
|
+
const {b}=this.s.context(worker,agent),e=parseEnvelope(b.job.goal);
|
|
37
|
+
if(!e.search)throw Error('SOURCE_SEARCH_NOT_AUTHORIZED');
|
|
38
|
+
if(!isSearchJobVersion(b.job.version))throw Error('SOURCE_SEARCH_VERSION_REQUIRED');
|
|
39
|
+
if(this.state!=='ready')throw Error('SOURCE_SEARCH_UNAVAILABLE');
|
|
40
|
+
if(e.search.model_policy.provider!=='deepseek-official')throw Error('SOURCE_SEARCH_PROVIDER_UNSUPPORTED');
|
|
41
|
+
return e.search;
|
|
42
|
+
}
|
|
43
|
+
capabilities(){return {enabled:this.state==='ready',state:this.state,contract:1,providers:['deepseek-official'],model:'explicit per-task search stage; no fallback',reasoningEffort:'disabled',max_requests_per_run:2,shared_model_dispatch_limit:6,max_results:5,credential:'Host-only public credential resolver; never copied to worker',page_content_read:false};}
|
|
44
|
+
uncertain(job){
|
|
45
|
+
const runs=this.g.scheduler.jobs.db.prepare('SELECT id FROM runs WHERE job_id=?').all(job.id);
|
|
46
|
+
return runs.some(({id})=>this.db.prepare("SELECT event_id,state FROM task_search_operations WHERE run_id=? AND state IN ('pending','uncertain')").all(id).some(o=>o.state==='uncertain'||!this.pending.has(o.event_id)));
|
|
47
|
+
}
|
|
48
|
+
async run(worker,agent,a,callId,signal){
|
|
49
|
+
if(!object(a)||Object.keys(a).some(k=>k!=='query')||typeof a.query!=='string'||!a.query.trim()||a.query.length>300||/[\x00-\x1f]/.test(a.query)||typeof callId!=='string'||!callId||callId.length>256)throw Error('SOURCE_ARGUMENT_INVALID');
|
|
50
|
+
const {b,revision}=this.s.context(worker,agent),policy=this.policy(worker,agent);if(b.report)throw Error('SOURCE_BATCH_ALREADY_FINAL');
|
|
51
|
+
const event='search:'+b.job.run_id+':'+callId,fp=sha(JSON.stringify([b.job.task_id,revision,b.job.claim,a.query,policy]));
|
|
52
|
+
const old=this.db.prepare('SELECT * FROM task_search_operations WHERE event_id=?').get(event);
|
|
53
|
+
if(old){if(old.fingerprint!==fp)throw Error('SOURCE_EVENT_CONFLICT');const saved=this.db.prepare('SELECT record FROM task_source_reads WHERE event_id=?').get(event);if(saved)return {...this.s.result(JSON.parse(saved.record)),replayed:true};if(this.pending.has(event))return this.pending.get(event);throw Error(old.error??'SOURCE_OPERATION_UNCERTAIN');}
|
|
54
|
+
if(this.uncertain(b.job))throw Error('SOURCE_SEARCH_DISPATCH_UNCERTAIN');
|
|
55
|
+
this.s.checkReadLimit(b.job.run_id);
|
|
56
|
+
if(this.db.prepare('SELECT count(*) n FROM task_search_operations WHERE run_id=?').get(b.job.run_id).n>=policy.max_requests)throw Error('SOURCE_SEARCH_BUDGET_EXHAUSTED');
|
|
57
|
+
const deadline=AbortSignal.any([b.signal,signal,AbortSignal.timeout(45000)].filter(Boolean));deadline.throwIfAborted();
|
|
58
|
+
this.db.prepare("INSERT INTO task_search_operations VALUES (?,?,?,'pending',NULL,NULL,?)").run(event,fp,b.job.run_id,this.g.now());
|
|
59
|
+
let recorded=false,returned=false;
|
|
60
|
+
const record=request=>{
|
|
61
|
+
deadline.throwIfAborted();this.policy(worker,agent);if(b.report)throw Error('SOURCE_BATCH_ALREADY_FINAL');
|
|
62
|
+
const expected={endpoint:base+'/messages',apiVersion:'2023-06-01',body:{model:policy.model_policy.model,max_tokens:2048,messages:[{role:'user',content:[{type:'text',text:'Perform a web search for the query: '+a.query}]}],tools:[{type:'web_search_20250305',name:'web_search',max_uses:1}],thinking:{type:'disabled'}}};
|
|
63
|
+
// Structural comparison doesn't accept extra messages, tools, hidden context or default models.
|
|
64
|
+
if(recorded||!same(request,expected))throw Error('SOURCE_SEARCH_REQUEST_CHANGED');
|
|
65
|
+
worker.reserveSearchRequest(agent,{...policy.model_policy,maxTokens:2048});
|
|
66
|
+
this.db.prepare('UPDATE task_search_operations SET request=? WHERE event_id=?').run(JSON.stringify(expected),event);recorded=true;
|
|
67
|
+
};
|
|
68
|
+
const work=Promise.resolve().then(async()=>{try{
|
|
69
|
+
const result=await this.reader.search(a.query,policy.model_policy,deadline,record);returned=true;deadline.throwIfAborted();
|
|
70
|
+
this.policy(worker,agent);if(b.report)throw Error('SOURCE_BATCH_ALREADY_FINAL');if(!recorded)throw Error('SOURCE_SEARCH_DISPATCH_UNVERIFIED');
|
|
71
|
+
if(!object(result)||!Array.isArray(result.sources)||result.sources.length>100||typeof result.truncated!=='boolean')throw Error('SOURCE_SEARCH_RESULT_INVALID');
|
|
72
|
+
const id='evidence-'+sha(event).slice(0,40),seen=new Set(),items=[];let rejected=0;
|
|
73
|
+
for(const raw of result.sources){
|
|
74
|
+
let url;try{url=sourceUrl(raw?.url).href;}catch{rejected++;continue;}
|
|
75
|
+
if(seen.has(url))continue;seen.add(url);
|
|
76
|
+
if(['title','snippet','publishedAt'].some(k=>raw[k]!==undefined&&(typeof raw[k]!=='string'||raw[k].includes('\0')||raw[k].length>(k==='snippet'?8000:k==='title'?500:128))))throw Error('SOURCE_SEARCH_RESULT_INVALID');
|
|
77
|
+
if(items.length<5)items.push({url,...Object.fromEntries(['title','snippet','publishedAt'].filter(k=>raw[k]!==undefined).map(k=>[k,raw[k]])),source_id:'search-source-'+sha(id+':'+url).slice(0,32)});
|
|
78
|
+
}
|
|
79
|
+
if(!items.length&&rejected)throw Error('SOURCE_SEARCH_RESULT_INVALID');
|
|
80
|
+
const content=JSON.stringify({query:a.query,sources:items,truncated:result.truncated||seen.size>5,rejected_urls:rejected,page_content_read:false});
|
|
81
|
+
if(Buffer.byteLength(content)>65536)throw Error('SOURCE_TOO_LARGE');
|
|
82
|
+
const r={id,source_id:'search-'+sha(event).slice(0,32),task_id:b.job.task_id,spec_revision:revision,run_id:b.job.run_id,claim:b.job.claim,title:'搜索:'+a.query.slice(0,100),kind:'search',uri:null,host:this.g.c.role,format:'json',size:Buffer.byteLength(content),sha256:sha(content),read_at:this.g.now(),content,search:{query:a.query,scope:policy.scope,...policy.model_policy,max_server_uses:1,page_content_read:false}};
|
|
83
|
+
this.db.exec('BEGIN IMMEDIATE');try{this.db.prepare('INSERT INTO task_source_reads VALUES (?,?,?,?,?,?)').run(id,r.task_id,r.run_id,event,fp,JSON.stringify(r));this.db.prepare("UPDATE task_search_operations SET state='completed' WHERE event_id=?").run(event);this.db.exec('COMMIT');}catch(e){this.db.exec('ROLLBACK');throw e;}
|
|
84
|
+
return this.s.result(r);
|
|
85
|
+
}catch(e){const uncertain=recorded&&!returned,code=uncertain?'SOURCE_SEARCH_DISPATCH_UNCERTAIN':deadline.aborted?'SOURCE_SEARCH_ABORTED':/^SOURCE_[A-Z_]+$/.test(e?.message)?e.message:e?.message==='WORKER_REQUEST_BUDGET'?'SOURCE_SEARCH_MODEL_BUDGET_EXHAUSTED':/^WEB_[A-Z_]+$/.test(e?.code)?'SOURCE_'+e.code:'SOURCE_SEARCH_UNAVAILABLE';this.db.prepare('UPDATE task_search_operations SET state=?,error=? WHERE event_id=?').run(uncertain?'uncertain':'failed',code,event);throw Error(code);}
|
|
86
|
+
finally{this.pending.delete(event);}});this.pending.set(event,work);return work;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function same(a,b){if(a===b)return true;if(!a||!b||typeof a!=='object'||typeof b!=='object'||Array.isArray(a)!==Array.isArray(b))return false;const keys=Object.keys(a);return keys.length===Object.keys(b).length&&keys.every(k=>Object.hasOwn(b,k)&&same(a[k],b[k]));}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Public official adapter only. No native settings mutation, browser identity, search or model calls.
|
|
2
|
+
export function sourceUrl(value){
|
|
3
|
+
let u;try{u=new URL(value);}catch{throw Error('SOURCE_URL_INVALID');}
|
|
4
|
+
if(u.protocol!=='https:'||u.username||u.password||u.port&&u.port!=='443'||!u.hostname.includes('.')||u.hostname.startsWith('[')||/^[\d.]+$/.test(u.hostname)||/\.(local|localhost|internal)$/i.test(u.hostname))throw Error('SOURCE_URL_DENIED');
|
|
5
|
+
if([...u.searchParams.keys()].some(k=>/^(?:access_?token|api_?key|token|secret|password|authorization|credential|signature)$/i.test(k)))throw Error('SOURCE_URL_CREDENTIALS_DENIED');
|
|
6
|
+
u.hash='';return u;
|
|
7
|
+
}
|
|
8
|
+
export async function createAnonymousWebReader(){
|
|
9
|
+
const [{HttpFetchProvider},{proxyRouteFor}]=await Promise.all([import('@deepseek-ai/dsh-web-fetch-http'),import('@deepseek-ai/dsh-http-proxy')]);
|
|
10
|
+
const provider=new HttpFetchProvider({maxResponseBytes:65536,maxBodyChars:65536,timeoutMs:15000,maxRedirects:2,userAgent:'dsh-task-gateway/0.18 (readonly-source)'});
|
|
11
|
+
return {async fetch(url,signal){
|
|
12
|
+
const u=sourceUrl(url);
|
|
13
|
+
// Do not bypass a native/operator proxy or pretend its DNS can be locally pinned.
|
|
14
|
+
if(proxyRouteFor(u).proxied||Object.entries(process.env).some(([k,v])=>/^(?:https?|all)_proxy$/i.test(k)&&v))throw Error('SOURCE_PROXY_UNSUPPORTED');
|
|
15
|
+
return provider.fetch({url:u.href},signal);
|
|
16
|
+
}};
|
|
17
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {spawn} from 'node:child_process';
|
|
2
|
+
// Own only this child. Never pkill, alter known_hosts, or infer task idleness.
|
|
3
|
+
export class SshConnector {
|
|
4
|
+
constructor(c,trace,io={}){
|
|
5
|
+
if(!/^127\.0\.0\.1:\d+:127\.0\.0\.1:\d+$/.test(c.forward)||!/^root@[a-zA-Z0-9.-]+$/.test(c.target)||typeof c.identityFile!=='string')throw Error('INVALID_SSH_CONFIG');
|
|
6
|
+
this.c=c;this.trace=trace;this.spawn=io.spawn??spawn;this.base=io.baseMs??2000;this.cap=io.maxMs??60000;this.failures=0;this.closed=false;this.lastExit=null;this.nextAttempt=null;
|
|
7
|
+
}
|
|
8
|
+
start(){
|
|
9
|
+
if(this.closed||this.child)return;
|
|
10
|
+
this.nextAttempt=null;const c=this.c,started=Date.now();let child;
|
|
11
|
+
try{child=this.spawn('/usr/bin/ssh',['-N','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','ExitOnForwardFailure=yes','-o','ConnectTimeout=8','-o','ServerAliveInterval=30','-o','ServerAliveCountMax=2','-i',c.identityFile,'-L',c.forward,c.target],{stdio:'ignore'});}catch{this.retry();return;}
|
|
12
|
+
this.child=child;
|
|
13
|
+
child.on('error',()=>this.trace('connector-error'));
|
|
14
|
+
child.once('close',code=>{if(this.child===child)this.child=null;this.lastExit={at:Date.now(),code};this.trace('connector-exit',{code});if(Date.now()-started>=60000)this.failures=0;this.retry();});
|
|
15
|
+
}
|
|
16
|
+
retry(){if(this.closed||this.timer)return;const delay=Math.min(this.cap,this.base*2**Math.min(this.failures++,10));this.nextAttempt=Date.now()+delay;this.timer=setTimeout(()=>{this.timer=null;this.start();},delay);this.timer.unref?.();}
|
|
17
|
+
snapshot(){return {state:this.closed?'closed':this.child?'process_running':this.timer?'backoff':'not_started',failures:this.failures,last_exit:this.lastExit,next_attempt_at:this.nextAttempt,proves_application_health:false};}
|
|
18
|
+
close(){
|
|
19
|
+
if(this.closing)return this.closing;
|
|
20
|
+
this.closed=true;clearTimeout(this.timer);const child=this.child;
|
|
21
|
+
this.closing=!child?Promise.resolve():new Promise(resolve=>{const timer=setTimeout(()=>child.kill('SIGKILL'),2000);child.once('close',()=>{clearTimeout(timer);resolve();});child.kill();});
|
|
22
|
+
return this.closing;
|
|
23
|
+
}
|
|
24
|
+
}
|
package/bundle/store.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
2
|
+
import {mkdirSync,readFileSync,writeFileSync,renameSync,openSync,fsyncSync,closeSync} from 'node:fs';
|
|
3
|
+
import {join} from 'node:path';
|
|
4
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
5
|
+
import {sameNativeTask} from './task-envelope.js';
|
|
6
|
+
|
|
7
|
+
export const hash=value=>createHash('sha256').update(value).digest('hex');
|
|
8
|
+
export class Coordinator {
|
|
9
|
+
constructor(root, writer = null) {
|
|
10
|
+
this.writer = writer;
|
|
11
|
+
this.root=root;mkdirSync(root,{recursive:true,mode:0o700});
|
|
12
|
+
this.db=new DatabaseSync(join(root,'tasks.sqlite'));
|
|
13
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
|
|
14
|
+
CREATE TABLE IF NOT EXISTS tasks(id TEXT PRIMARY KEY,task_key TEXT UNIQUE,owner TEXT,epoch INTEGER,busy INTEGER,revision INTEGER,blocked INTEGER DEFAULT 0,checkpoint TEXT);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS ingress(id TEXT PRIMARY KEY,task_id TEXT,source TEXT,node TEXT,goal TEXT);
|
|
16
|
+
CREATE TABLE IF NOT EXISTS intents(seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE,task_id TEXT,node TEXT,fingerprint TEXT,content TEXT,base_hash TEXT,status TEXT,epoch INTEGER,receipt TEXT);
|
|
17
|
+
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,type TEXT,data TEXT);`);
|
|
18
|
+
}
|
|
19
|
+
tx(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
|
20
|
+
log(type,data){this.db.prepare('INSERT INTO audit(type,data) VALUES (?,?)').run(type,JSON.stringify(data));}
|
|
21
|
+
task(id){const t=this.db.prepare('SELECT * FROM tasks WHERE id=?').get(id);if(!t)throw Error('TASK_NOT_FOUND');return t;}
|
|
22
|
+
file(id){this.task(id);return join(this.root,'workspaces',id,'artifact.txt');}
|
|
23
|
+
contents(id){if(this.writer)return this.writer.contents(id);try{return readFileSync(this.file(id),'utf8');}catch(e){if(e.code==='ENOENT')return '';throw e;}}
|
|
24
|
+
status(id){const t=this.task(id);return {...t,fileHash:hash(this.contents(id)),intents:this.db.prepare('SELECT id,node,status,epoch FROM intents WHERE task_id=? ORDER BY seq').all(id)};}
|
|
25
|
+
accept(node,{task_key,ingress_id,source,goal=""}){
|
|
26
|
+
if(!["local","cloud"].includes(node)||typeof goal!=="string"||goal.length>12000||typeof source!=="string"||source.length>64)throw Error("INVALID_INGRESS");
|
|
27
|
+
if(!/^[a-z0-9-]{1,64}$/.test(task_key)||typeof ingress_id!=='string'||ingress_id.length>256)throw Error('INVALID_INGRESS');
|
|
28
|
+
return this.tx(()=>{
|
|
29
|
+
let t=this.db.prepare('SELECT * FROM tasks WHERE task_key=?').get(task_key);
|
|
30
|
+
const old=this.db.prepare('SELECT * FROM ingress WHERE id=?').get(ingress_id);
|
|
31
|
+
if(old){if(!t||old.task_id!==t.id||old.source!==source||old.node!==node||old.goal!==goal)throw Error('INGRESS_ID_CONFLICT');return this.status(t.id);}
|
|
32
|
+
if(t){const first=this.db.prepare('SELECT goal FROM ingress WHERE task_id=? ORDER BY rowid LIMIT 1').get(t.id);
|
|
33
|
+
if(first&&!sameNativeTask(first.goal,goal))throw Error('TASK_CONTENT_CONFLICT');}
|
|
34
|
+
if(!t){const id='task-'+randomUUID();this.db.prepare('INSERT INTO tasks(id,task_key,owner,epoch,busy,revision) VALUES (?,?,?,1,0,0)').run(id,task_key,'cloud');t=this.task(id);}
|
|
35
|
+
this.db.prepare('INSERT INTO ingress VALUES (?,?,?,?,?)').run(ingress_id,t.id,source,node,goal);
|
|
36
|
+
this.log('accepted',{node,source,ingress_id,task_id:t.id});return this.status(t.id);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
fence(node,id,epoch){const t=this.task(id);if(t.owner!==node||t.epoch!==epoch)throw Error('STALE_FENCE');if(t.blocked)throw Error('NEEDS_REVIEW');return t;}
|
|
40
|
+
begin(node,{task_id,epoch}){return this.tx(()=>{const t=this.fence(node,task_id,epoch);if(t.busy)throw Error('TASK_BUSY');this.db.prepare('UPDATE tasks SET busy=1 WHERE id=?').run(task_id);this.log('busy',{task_id,node,epoch});return this.status(task_id);});}
|
|
41
|
+
drain(id){
|
|
42
|
+
const t=this.task(id);if(t.busy||t.blocked)return;
|
|
43
|
+
const q=this.db.prepare("SELECT * FROM intents WHERE task_id=? AND status='queued' ORDER BY seq LIMIT 1").get(id);if(!q)return;
|
|
44
|
+
this.db.prepare('UPDATE tasks SET owner=?,epoch=epoch+1,busy=1 WHERE id=?').run(q.node,id);
|
|
45
|
+
this.db.prepare("UPDATE intents SET status='granted',epoch=? WHERE id=?").run(t.epoch+1,q.id);
|
|
46
|
+
this.log('handoff',{task_id:id,from:t.owner,to:q.node,epoch:t.epoch+1,intent:q.id});
|
|
47
|
+
}
|
|
48
|
+
request(node,{task_id,request_id,content,base_hash}){
|
|
49
|
+
if(this.writer)this.writer.assertBound(task_id);
|
|
50
|
+
if(typeof request_id!=='string'||!request_id||request_id.length>128||typeof content!=='string'||Buffer.byteLength(content)>4096||!(/^[a-f0-9]{64}$/).test(base_hash))throw Error('INVALID_WRITE');
|
|
51
|
+
return this.tx(()=>{
|
|
52
|
+
this.task(task_id);const fingerprint=hash(JSON.stringify({task_id,node,content,base_hash}));
|
|
53
|
+
const old=this.db.prepare('SELECT * FROM intents WHERE id=?').get(request_id);
|
|
54
|
+
if(old){if(old.fingerprint!==fingerprint)throw Error('INTENT_ID_CONFLICT');return {intent:this.intent(request_id),task:this.status(task_id)};}
|
|
55
|
+
this.db.prepare("INSERT INTO intents(id,task_id,node,fingerprint,content,base_hash,status) VALUES (?,?,?,?,?,?,'queued')").run(request_id,task_id,node,fingerprint,content,base_hash);
|
|
56
|
+
this.log('write-request',{task_id,node,request_id});this.drain(task_id);
|
|
57
|
+
return {intent:this.intent(request_id),task:this.status(task_id)};
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
intent(id){const q=this.db.prepare('SELECT * FROM intents WHERE id=?').get(id);if(!q)throw Error('INTENT_NOT_FOUND');return q;}
|
|
61
|
+
apply(node,{request_id,epoch}){
|
|
62
|
+
// A durable intent precedes the filesystem effect. Ambiguous effects remain fenced.
|
|
63
|
+
const q=this.tx(()=>{
|
|
64
|
+
const q=this.intent(request_id);if(q.node!==node)throw Error('WRITER_DENIED');
|
|
65
|
+
if(q.status==='applied')return q;
|
|
66
|
+
this.fence(node,q.task_id,epoch);
|
|
67
|
+
if(q.status!=='granted'||q.epoch!==epoch)throw Error('NOT_GRANTED');
|
|
68
|
+
if(hash(this.contents(q.task_id))!==q.base_hash)throw Error('BASE_HASH_CONFLICT');
|
|
69
|
+
this.db.prepare("UPDATE intents SET status='writing' WHERE id=?").run(q.id);return q;
|
|
70
|
+
});
|
|
71
|
+
if(q.status==='applied')return JSON.parse(q.receipt);
|
|
72
|
+
try{
|
|
73
|
+
let commit;
|
|
74
|
+
if(this.writer)commit=this.writer.write(q);else {
|
|
75
|
+
const dir=join(this.root,'workspaces',q.task_id);mkdirSync(dir,{recursive:true,mode:0o700});
|
|
76
|
+
const temporary=join(dir,'.pending-'+randomUUID());writeFileSync(temporary,q.content,{mode:0o600,flag:'wx'});
|
|
77
|
+
const fd=openSync(temporary,'r');try{fsyncSync(fd);}finally{closeSync(fd);}
|
|
78
|
+
renameSync(temporary,this.file(q.task_id));
|
|
79
|
+
const directory=openSync(dir,'r');try{fsyncSync(directory);}finally{closeSync(directory);}
|
|
80
|
+
}
|
|
81
|
+
return this.tx(()=>{
|
|
82
|
+
this.fence(node,q.task_id,epoch);
|
|
83
|
+
const receipt={request_id:q.id,task_id:q.task_id,node,epoch,sha256:hash(q.content),...(commit?{commit}:{})};
|
|
84
|
+
this.db.prepare("UPDATE intents SET status='applied',receipt=? WHERE id=?").run(JSON.stringify(receipt),q.id);
|
|
85
|
+
this.db.prepare('UPDATE tasks SET revision=revision+1 WHERE id=?').run(q.task_id);
|
|
86
|
+
this.log('write-applied',receipt);return receipt;
|
|
87
|
+
});
|
|
88
|
+
}catch(e){this.db.prepare('UPDATE tasks SET blocked=1 WHERE id=?').run(q.task_id);throw e;}
|
|
89
|
+
}
|
|
90
|
+
safe(node,{task_id,epoch,checkpoint}){
|
|
91
|
+
if(typeof checkpoint!=='string'||!checkpoint.trim()||checkpoint.length>2048)throw Error('CHECKPOINT_REQUIRED');
|
|
92
|
+
return this.tx(()=>{
|
|
93
|
+
this.fence(node,task_id,epoch);
|
|
94
|
+
const pending=this.db.prepare("SELECT count(*) AS n FROM intents WHERE task_id=? AND status IN ('granted','writing')").get(task_id).n;
|
|
95
|
+
if(pending)throw Error('WRITES_NOT_QUIESCENT');
|
|
96
|
+
this.db.prepare('UPDATE tasks SET busy=0,checkpoint=? WHERE id=?').run(checkpoint,task_id);
|
|
97
|
+
this.log('safe-point',{task_id,node,epoch});this.drain(task_id);return this.status(task_id);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
snapshot(){return {tasks:this.db.prepare('SELECT * FROM tasks').all(),ingress:this.db.prepare('SELECT * FROM ingress').all(),intents:this.db.prepare('SELECT id,task_id,node,status,epoch FROM intents').all(),audit:this.db.prepare('SELECT * FROM audit').all().map(x=>({...x,data:JSON.parse(x.data)}))};}
|
|
101
|
+
close(){this.db.close();}
|
|
102
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import {validateModelObservation} from './a2a-dispatches.js';
|
|
2
|
+
import {createHash, randomUUID} from 'node:crypto';
|
|
3
|
+
import {validSources, validPolicy} from './task-context.js';
|
|
4
|
+
import {parseEnvelope} from './task-envelope.js';
|
|
5
|
+
import {tx} from './recovery.js';
|
|
6
|
+
|
|
7
|
+
const json = JSON.stringify;
|
|
8
|
+
const hash = x => createHash('sha256').update(json(x)).digest('hex');
|
|
9
|
+
const other = role => role === 'local' ? 'cloud' : 'local';
|
|
10
|
+
const activeRequests = new Set(['claimed', 'running', 'stopping']);
|
|
11
|
+
const text = (x, n = 256) => typeof x === 'string' && !!x.trim() && x.length <= n;
|
|
12
|
+
function shape(x, keys) {
|
|
13
|
+
if (!x || typeof x !== 'object' || Array.isArray(x) || Object.keys(x).some(k => !keys.includes(k))) throw Error('A2A_ARGUMENT_INVALID');
|
|
14
|
+
}
|
|
15
|
+
function human(node, a) {
|
|
16
|
+
const sources = validSources(a.sources);
|
|
17
|
+
if (!sources.length || sources.some(s => s.role !== node)) throw Error('CONTEXT_ORIGIN_MISMATCH');
|
|
18
|
+
if (!text(a.authorization_quote, 4000) || !sources.at(-1).text.includes(a.authorization_quote)) throw Error('A2A_AUTHORIZATION_REQUIRED');
|
|
19
|
+
if (!text(a.event_id)) throw Error('A2A_EVENT_INVALID');
|
|
20
|
+
return sources;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Cloud authority. Peer text never creates a grant. The separate endpoint must validate
|
|
24
|
+
// this ledger before each model/tool dispatch; broker storage is not execution proof.
|
|
25
|
+
export class TaskA2A {
|
|
26
|
+
constructor(g) {
|
|
27
|
+
this.g = g; this.db = g.db; this.now = g.now;
|
|
28
|
+
this.db.exec(`
|
|
29
|
+
CREATE TABLE IF NOT EXISTS a2a_grants(
|
|
30
|
+
id TEXT PRIMARY KEY,event_id TEXT UNIQUE NOT NULL,fingerprint TEXT NOT NULL,
|
|
31
|
+
task_id TEXT NOT NULL,revision INTEGER NOT NULL,goal_hash TEXT NOT NULL,scope TEXT NOT NULL,
|
|
32
|
+
source TEXT NOT NULL,status TEXT NOT NULL,epoch INTEGER NOT NULL,end_at INTEGER NOT NULL,
|
|
33
|
+
max_turns INTEGER NOT NULL,max_requests INTEGER NOT NULL,reply_timeout INTEGER NOT NULL,
|
|
34
|
+
used_turns INTEGER NOT NULL DEFAULT 0,used_requests INTEGER NOT NULL DEFAULT 0,
|
|
35
|
+
reason TEXT,created INTEGER NOT NULL,UNIQUE(task_id,revision));
|
|
36
|
+
CREATE TABLE IF NOT EXISTS a2a_requests(
|
|
37
|
+
id TEXT PRIMARY KEY,grant_id TEXT NOT NULL,parent_id TEXT UNIQUE,origin TEXT NOT NULL,
|
|
38
|
+
destination TEXT NOT NULL,instruction TEXT NOT NULL,state TEXT NOT NULL,deadline INTEGER NOT NULL,
|
|
39
|
+
claim TEXT,instance TEXT,epoch INTEGER,lease_until INTEGER,session_id TEXT,
|
|
40
|
+
result TEXT,result_hash TEXT,late_result TEXT,error TEXT,drained_at INTEGER,created INTEGER NOT NULL);
|
|
41
|
+
CREATE INDEX IF NOT EXISTS a2a_pending ON a2a_requests(destination,state,created);
|
|
42
|
+
CREATE TABLE IF NOT EXISTS a2a_events(event_id TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,result TEXT NOT NULL);
|
|
43
|
+
CREATE TABLE IF NOT EXISTS a2a_dispatches(id TEXT PRIMARY KEY,request_id TEXT NOT NULL,fingerprint TEXT NOT NULL,record TEXT NOT NULL,created INTEGER NOT NULL);
|
|
44
|
+
CREATE TABLE IF NOT EXISTS a2a_model_observations(id TEXT PRIMARY KEY,request_id TEXT NOT NULL,record TEXT NOT NULL);
|
|
45
|
+
CREATE TABLE IF NOT EXISTS a2a_audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,grant_id TEXT NOT NULL,type TEXT NOT NULL,data TEXT NOT NULL,at INTEGER NOT NULL);
|
|
46
|
+
`);
|
|
47
|
+
}
|
|
48
|
+
audit(id, type, data = {}) { this.db.prepare('INSERT INTO a2a_audit(grant_id,type,data,at) VALUES (?,?,?,?)').run(id, type, json(data), this.now()); }
|
|
49
|
+
get(id) { const r = this.db.prepare('SELECT * FROM a2a_grants WHERE id=?').get(id); if (!r) throw Error('A2A_GRANT_NOT_FOUND'); return r; }
|
|
50
|
+
request(id) { const r = this.db.prepare('SELECT * FROM a2a_requests WHERE id=?').get(id); if (!r) throw Error('A2A_REQUEST_NOT_FOUND'); return r; }
|
|
51
|
+
requests(id) { return this.db.prepare('SELECT * FROM a2a_requests WHERE grant_id=? ORDER BY created,rowid').all(id); }
|
|
52
|
+
busy(task) {
|
|
53
|
+
return !!this.db.prepare("SELECT 1 FROM a2a_requests r JOIN a2a_grants g ON g.id=r.grant_id WHERE g.task_id=? AND (r.state IN ('queued','claimed','running','stopping') OR (r.state='needs_review' AND r.drained_at IS NULL))").get(task);
|
|
54
|
+
}
|
|
55
|
+
current(w) {
|
|
56
|
+
const h = this.g.catalog.head(w.task_id), t = this.g.store.task(w.task_id);
|
|
57
|
+
if (h.spec_revision !== w.revision || hash(h.goal) !== w.goal_hash) throw Error('A2A_TASK_REVISION_CHANGED');
|
|
58
|
+
if (t.blocked) throw Error('TASK_BLOCKED');
|
|
59
|
+
if (t.busy) throw Error('A2A_TASK_BUSY');
|
|
60
|
+
if (w.end_at <= this.now()) throw Error('A2A_GRANT_EXPIRED');
|
|
61
|
+
return h;
|
|
62
|
+
}
|
|
63
|
+
view(w) {
|
|
64
|
+
return {id:w.id, task_id:w.task_id, spec_revision:w.revision, state:w.status, epoch:w.epoch,
|
|
65
|
+
scope:JSON.parse(w.scope), budget:{turns:w.used_turns, max_turns:w.max_turns, model_requests:w.used_requests, max_model_requests:w.max_requests, end_at:w.end_at, reply_timeout_seconds:w.reply_timeout},
|
|
66
|
+
reason:w.reason, execution:'bounded-readonly-a2a', development:false, publish:false,
|
|
67
|
+
requests:this.requests(w.id).map(r => ({id:r.id, parent_id:r.parent_id, from:r.origin, to:r.destination, state:r.state,
|
|
68
|
+
deadline:r.deadline, session_id:r.session_id, result:r.result ? JSON.parse(r.result) : null,model_calls:this.db.prepare('SELECT record FROM a2a_model_observations WHERE request_id=? ORDER BY rowid').all(r.id).map(x=>JSON.parse(x.record)),
|
|
69
|
+
late_result:r.late_result ? JSON.parse(r.late_result) : null, error:r.error, drained:r.drained_at !== null}))};
|
|
70
|
+
}
|
|
71
|
+
list(task) { this.g.store.task(task); this.reap(); return {items:this.db.prepare('SELECT * FROM a2a_grants WHERE task_id=? ORDER BY created,rowid').all(task).map(w => this.view(w)), authority:'cloud'}; }
|
|
72
|
+
create(node, a) {
|
|
73
|
+
shape(a, ['task_id','expected_revision','scope','end_at','max_turns','max_model_requests','reply_timeout_seconds','sources','authorization_quote','event_id']);
|
|
74
|
+
const sources = human(node, a);
|
|
75
|
+
shape(a.scope, ['local','cloud']);
|
|
76
|
+
const scope = {};
|
|
77
|
+
for (const role of ['local','cloud']) {
|
|
78
|
+
const s = a.scope[role]; shape(s, ['model_policy','capabilities','references']);
|
|
79
|
+
const policy = validPolicy(s.model_policy);
|
|
80
|
+
// No model fallback. high applies only to this newly authorized cloud stage.
|
|
81
|
+
if (role === 'cloud' && policy.reasoningEffort === undefined) policy.reasoningEffort = 'high';
|
|
82
|
+
if (!Array.isArray(s.capabilities) || !s.capabilities.length || new Set(s.capabilities).size !== s.capabilities.length || s.capabilities.some(k => !['context','file_text'].includes(k)) || !s.capabilities.includes('context')) throw Error('A2A_CAPABILITY_INVALID');
|
|
83
|
+
if (!Array.isArray(s.references ?? []) || (s.references ?? []).length > 8 || new Set(s.references ?? []).size !== (s.references ?? []).length || (s.references ?? []).some(x => !text(x,1000))) throw Error('A2A_REFERENCE_INVALID');
|
|
84
|
+
if ((s.references ?? []).length && !s.capabilities.includes('file_text')) throw Error('A2A_CAPABILITY_INVALID');
|
|
85
|
+
scope[role] = {model_policy:policy, capabilities:[...s.capabilities].sort(), references:[...(s.references ?? [])].sort()};
|
|
86
|
+
}
|
|
87
|
+
const fp = hash({node,...a,scope,sources});
|
|
88
|
+
const old = this.db.prepare('SELECT * FROM a2a_grants WHERE event_id=?').get(a.event_id);
|
|
89
|
+
if (old) { if (old.fingerprint !== fp) throw Error('A2A_EVENT_CONFLICT'); return this.view(old); }
|
|
90
|
+
const h = this.g.catalog.head(a.task_id), e = parseEnvelope(h.goal);
|
|
91
|
+
if (h.legacy || !e || e.intent !== 'plan') throw Error('A2A_PLAN_TASK_REQUIRED');
|
|
92
|
+
if (h.spec_revision !== a.expected_revision) throw Error('TASK_REVISION_CONFLICT');
|
|
93
|
+
if (!Number.isSafeInteger(a.end_at) || a.end_at <= this.now() || a.end_at > this.now()+366*86400000 ||
|
|
94
|
+
!Number.isInteger(a.max_turns) || a.max_turns < 1 || a.max_turns > 12 ||
|
|
95
|
+
!Number.isInteger(a.max_model_requests) || a.max_model_requests < 1 || a.max_model_requests > 72 ||
|
|
96
|
+
!Number.isInteger(a.reply_timeout_seconds) || a.reply_timeout_seconds < 60 || a.reply_timeout_seconds > 7*86400) throw Error('A2A_BUDGET_INVALID');
|
|
97
|
+
for (const role of ['local','cloud']) for (const uri of scope[role].references) {
|
|
98
|
+
if (!(e.task_context?.references ?? []).some(r => r.kind === 'file-reference' && r.host === role && r.uri === uri)) throw Error('A2A_REFERENCE_NOT_IN_TASK');
|
|
99
|
+
}
|
|
100
|
+
this.g.assertTaskQuiescent(a.task_id);
|
|
101
|
+
const id = tx(this.db, () => {
|
|
102
|
+
if (this.db.prepare('SELECT 1 FROM a2a_grants WHERE task_id=? AND revision=?').get(a.task_id,h.spec_revision)) throw Error('A2A_REVISION_ALREADY_AUTHORIZED');
|
|
103
|
+
const id = 'collab-'+randomUUID();
|
|
104
|
+
this.db.prepare("INSERT INTO a2a_grants(id,event_id,fingerprint,task_id,revision,goal_hash,scope,source,status,epoch,end_at,max_turns,max_requests,reply_timeout,created) VALUES (?,?,?,?,?,?,?,?,'active',1,?,?,?,?,?)")
|
|
105
|
+
.run(id,a.event_id,fp,a.task_id,h.spec_revision,hash(h.goal),json(scope),json(sources),a.end_at,a.max_turns,a.max_model_requests,a.reply_timeout_seconds,this.now());
|
|
106
|
+
this.audit(id,'authorized',{origin:node,execution_started:false}); return id;
|
|
107
|
+
});
|
|
108
|
+
return this.view(this.get(id));
|
|
109
|
+
}
|
|
110
|
+
insertRequest(w, from, instruction, parent = null) {
|
|
111
|
+
if (w.used_turns >= w.max_turns) throw Error('A2A_TURN_BUDGET_EXHAUSTED');
|
|
112
|
+
const id = 'wake-'+randomUUID(), deadline = Math.min(w.end_at,this.now()+w.reply_timeout*1000);
|
|
113
|
+
this.db.prepare("INSERT INTO a2a_requests(id,grant_id,parent_id,origin,destination,instruction,state,deadline,created) VALUES (?,?,?,?,?,?,'queued',?,?)").run(id,w.id,parent,from,other(from),instruction,deadline,this.now());
|
|
114
|
+
this.db.prepare('UPDATE a2a_grants SET used_turns=used_turns+1 WHERE id=?').run(w.id);
|
|
115
|
+
this.audit(w.id,'queued',{request_id:id,parent_id:parent,from,to:other(from)}); return id;
|
|
116
|
+
}
|
|
117
|
+
start(node, a) {
|
|
118
|
+
shape(a, ['grant_id','instruction','sources','authorization_quote','event_id']); human(node,a);
|
|
119
|
+
if (!text(a.instruction,4000)) throw Error('A2A_INSTRUCTION_INVALID');
|
|
120
|
+
const fp = hash({node,...a});
|
|
121
|
+
return tx(this.db, () => {
|
|
122
|
+
const old = this.db.prepare('SELECT * FROM a2a_events WHERE event_id=?').get(a.event_id);
|
|
123
|
+
if (old) { if (old.fingerprint !== fp) throw Error('A2A_EVENT_CONFLICT'); return JSON.parse(old.result); }
|
|
124
|
+
const w = this.get(a.grant_id); this.current(w);
|
|
125
|
+
if (w.status !== 'active') throw Error('A2A_GRANT_INACTIVE');
|
|
126
|
+
if (this.requests(w.id).length) throw Error('A2A_ROOT_ALREADY_EXISTS');
|
|
127
|
+
this.g.assertTaskQuiescent(w.task_id);
|
|
128
|
+
const id = this.insertRequest(w,node,a.instruction), result = {grant_id:w.id, request_id:id, state:'queued', meaning:'waiting for authorized recipient; not executed'};
|
|
129
|
+
this.db.prepare('INSERT INTO a2a_events VALUES (?,?,?)').run(a.event_id,fp,json(result)); return result;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
reap() {
|
|
133
|
+
tx(this.db, () => {
|
|
134
|
+
for (const w of this.db.prepare("SELECT * FROM a2a_grants WHERE status IN ('active','paused')").all()) {
|
|
135
|
+
let code; try { this.current(w); } catch(e) { code=e.message; }
|
|
136
|
+
if (code) { this.stop(w,'invalidated',code); continue; }
|
|
137
|
+
for (const r of this.requests(w.id)) {
|
|
138
|
+
if (r.deadline <= this.now() && ['queued','claimed','running'].includes(r.state)) {
|
|
139
|
+
this.db.prepare('UPDATE a2a_requests SET state=?,error=?,drained_at=? WHERE id=?').run(r.state==='running'?'stopping':'timed_out','A2A_REPLY_TIMEOUT',r.state==='running'?null:this.now(),r.id);
|
|
140
|
+
this.db.prepare("UPDATE a2a_grants SET status='needs_review',reason='A2A_REPLY_TIMEOUT',epoch=epoch+1 WHERE id=?").run(w.id);
|
|
141
|
+
this.audit(w.id,'timeout',{request_id:r.id});
|
|
142
|
+
} else if (r.state === 'claimed' && r.lease_until <= this.now()) {
|
|
143
|
+
// Only a claim with no begin intent may return to the queue.
|
|
144
|
+
this.db.prepare("UPDATE a2a_requests SET state='queued',claim=NULL,instance=NULL,epoch=NULL,lease_until=NULL WHERE id=?").run(r.id);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
claim(node, a) {
|
|
151
|
+
shape(a,['instance_id']); if (!text(a.instance_id)) throw Error('A2A_INSTANCE_INVALID');
|
|
152
|
+
this.reap();
|
|
153
|
+
return tx(this.db, () => {
|
|
154
|
+
// A polling endpoint cannot acquire a second execution while its first is undrained.
|
|
155
|
+
if (this.db.prepare("SELECT 1 FROM a2a_requests WHERE destination=? AND state IN ('claimed','running','stopping')").get(node)) return {item:null,reason:'recipient_busy'};
|
|
156
|
+
const r = this.db.prepare("SELECT r.* FROM a2a_requests r JOIN a2a_grants g ON g.id=r.grant_id WHERE r.destination=? AND r.state='queued' AND g.status='active' ORDER BY r.created,r.rowid LIMIT 1").get(node);
|
|
157
|
+
if (!r) return {item:null,reason:'no_authorized_work'};
|
|
158
|
+
const w = this.get(r.grant_id); this.current(w); const claim=randomUUID();
|
|
159
|
+
this.db.prepare("UPDATE a2a_requests SET state='claimed',claim=?,instance=?,epoch=?,lease_until=? WHERE id=?").run(claim,a.instance_id,w.epoch,this.now()+30000,r.id);
|
|
160
|
+
this.audit(w.id,'claimed',{request_id:r.id,recipient:node});
|
|
161
|
+
return {item:this.materialize(this.request(r.id))};
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
owned(node,a) {
|
|
165
|
+
const r=this.request(a.request_id);
|
|
166
|
+
if (r.destination!==node || !text(a.claim) || r.claim!==a.claim || r.instance!==a.instance_id) throw Error('A2A_CLAIM_DENIED');
|
|
167
|
+
return r;
|
|
168
|
+
}
|
|
169
|
+
materialize(r) {
|
|
170
|
+
const w=this.get(r.grant_id), h=this.g.catalog.head(w.task_id), scope=JSON.parse(w.scope);
|
|
171
|
+
const lineage=[]; let p=r.parent_id;
|
|
172
|
+
while(p) { const prior=this.request(p); if(prior.grant_id!==w.id || lineage.length>=12)throw Error('A2A_LINEAGE_INVALID');lineage.push({request_id:prior.id,from:prior.origin,to:prior.destination,instruction:prior.instruction,result:prior.result?JSON.parse(prior.result):null});p=prior.parent_id; }
|
|
173
|
+
return {id:r.id,grant_id:w.id,task_id:w.task_id,spec_revision:w.revision,claim:r.claim,instance_id:r.instance,epoch:r.epoch,
|
|
174
|
+
from:r.origin,to:r.destination,instruction:r.instruction,parent_id:r.parent_id,deadline:r.deadline,session_id:r.session_id,
|
|
175
|
+
task_request:parseEnvelope(h.goal),scope:scope[r.destination],context:lineage.reverse(),
|
|
176
|
+
remaining_turns:w.max_turns-w.used_turns,remaining_model_requests:w.max_requests-w.used_requests,
|
|
177
|
+
peer_text_is_user_authority:false};
|
|
178
|
+
}
|
|
179
|
+
validate(node,a) {
|
|
180
|
+
shape(a,['request_id','claim','instance_id']); this.reap();
|
|
181
|
+
const r=this.owned(node,a), w=this.get(r.grant_id); this.current(w);
|
|
182
|
+
if(w.status!=='active'||r.epoch!==w.epoch||!['claimed','running'].includes(r.state)||r.deadline<=this.now())throw Error('A2A_EXECUTION_FENCED');
|
|
183
|
+
return {valid:true,state:r.state,deadline:r.deadline,grant_id:w.id,remaining_model_requests:w.max_requests-w.used_requests};
|
|
184
|
+
}
|
|
185
|
+
begin(node,a) {
|
|
186
|
+
this.validate(node,a);
|
|
187
|
+
return tx(this.db,()=>{
|
|
188
|
+
const r=this.owned(node,a);
|
|
189
|
+
if(r.state==='running')return {item:this.materialize(r),already_started:true};
|
|
190
|
+
const session='a2a-'+randomUUID();
|
|
191
|
+
this.db.prepare("UPDATE a2a_requests SET state='running',session_id=?,lease_until=NULL WHERE id=?").run(session,r.id);
|
|
192
|
+
this.audit(r.grant_id,'execution_intent',{request_id:r.id,session_id:session});
|
|
193
|
+
return {item:this.materialize(this.request(r.id)),already_started:false};
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
reserve(node,a) {
|
|
197
|
+
shape(a,['request_id','claim','instance_id','dispatch_id','model_policy']);
|
|
198
|
+
if(!text(a.dispatch_id))throw Error('A2A_DISPATCH_INVALID');const policy=validPolicy(a.model_policy);
|
|
199
|
+
this.validate(node,{request_id:a.request_id,claim:a.claim,instance_id:a.instance_id});
|
|
200
|
+
return tx(this.db,()=>{
|
|
201
|
+
const r=this.owned(node,a),w=this.get(r.grant_id),fp=hash({request_id:r.id,claim:r.claim,policy});
|
|
202
|
+
if(r.state!=='running')throw Error('A2A_EXECUTION_NOT_STARTED');
|
|
203
|
+
if(json(policy)!==json(JSON.parse(w.scope)[node].model_policy))throw Error('A2A_MODEL_POLICY_MISMATCH');
|
|
204
|
+
const old=this.db.prepare('SELECT * FROM a2a_dispatches WHERE id=?').get(a.dispatch_id);
|
|
205
|
+
if(old){if(old.fingerprint!==fp)throw Error('A2A_EVENT_CONFLICT');return {...JSON.parse(old.record),replayed:true};}
|
|
206
|
+
if(w.used_requests>=w.max_requests||this.db.prepare('SELECT count(*) n FROM a2a_dispatches WHERE request_id=?').get(r.id).n>=6)throw Error('A2A_MODEL_BUDGET_EXHAUSTED');
|
|
207
|
+
const record={reserved:true,dispatch_id:a.dispatch_id,request_id:r.id,model_policy:policy,replayed:false};
|
|
208
|
+
this.db.prepare('INSERT INTO a2a_dispatches VALUES (?,?,?,?,?)').run(a.dispatch_id,r.id,fp,json(record),this.now());
|
|
209
|
+
this.db.prepare('UPDATE a2a_grants SET used_requests=used_requests+1 WHERE id=?').run(w.id);
|
|
210
|
+
this.audit(w.id,'model_reserved',{request_id:r.id,dispatch_id:a.dispatch_id});return record;
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
recordModels(r,models=[]){
|
|
214
|
+
if(!Array.isArray(models)||models.length>6)throw Error('A2A_MODEL_OBSERVATION_INVALID');
|
|
215
|
+
const seen=new Set();for(const raw of models){const m=validateModelObservation(raw);if(seen.has(m.dispatch_id))throw Error('A2A_MODEL_OBSERVATION_INVALID');seen.add(m.dispatch_id);
|
|
216
|
+
const reserved=this.db.prepare('SELECT record FROM a2a_dispatches WHERE id=? AND request_id=?').get(m.dispatch_id,r.id);if(!reserved)throw Error('A2A_MODEL_RESERVATION_REQUIRED');
|
|
217
|
+
const p=JSON.parse(reserved.record).model_policy;
|
|
218
|
+
if(m.provider!==p.provider||m.model!==p.model||p.reasoningEffort!==undefined&&m.reasoningEffort!==p.reasoningEffort)throw Error('A2A_MODEL_POLICY_MISMATCH');
|
|
219
|
+
const old=this.db.prepare('SELECT record FROM a2a_model_observations WHERE id=?').get(m.dispatch_id);
|
|
220
|
+
if(old){if(old.record!==json(m))throw Error('A2A_MODEL_OBSERVATION_CONFLICT');}
|
|
221
|
+
else this.db.prepare('INSERT INTO a2a_model_observations VALUES (?,?,?)').run(m.dispatch_id,r.id,json(m));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
finish(node,a) {
|
|
225
|
+
shape(a,['request_id','claim','instance_id','result','model_calls']);shape(a.result,['summary','followup','evidence']);
|
|
226
|
+
if(a.result.evidence!==undefined){
|
|
227
|
+
if(!Array.isArray(a.result.evidence)||a.result.evidence.length>8)throw Error('A2A_EVIDENCE_INVALID');
|
|
228
|
+
const seen=new Set();for(const e of a.result.evidence){shape(e,['id','source_id','host','title','format','size','sha256','read_at']);
|
|
229
|
+
if(!text(e.id,100)||seen.has(e.id)||!text(e.source_id,100)||e.host!==node||!text(e.title,500)||!['markdown','text','json','csv'].includes(e.format)||!Number.isInteger(e.size)||e.size<0||e.size>65536||!/^[a-f0-9]{64}$/.test(e.sha256??'')||!Number.isSafeInteger(e.read_at))throw Error('A2A_EVIDENCE_INVALID');seen.add(e.id);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if(!text(a.result.summary,4000)||a.result.followup!==undefined&&!text(a.result.followup,4000))throw Error('A2A_RESULT_INVALID');
|
|
233
|
+
this.reap();
|
|
234
|
+
return tx(this.db,()=>{
|
|
235
|
+
const r=this.owned(node,a),w=this.get(r.grant_id),fp=hash(a.result);this.recordModels(r,a.model_calls);
|
|
236
|
+
if(r.result_hash){if(r.result_hash!==fp)throw Error('A2A_RESULT_CONFLICT');return {recorded:true,replayed:true,state:r.state};}
|
|
237
|
+
if(!['running','stopping','needs_review'].includes(r.state))throw Error('A2A_EXECUTION_NOT_STARTED');
|
|
238
|
+
// Teardown proof is supplied by the endpoint only after its owned agent is disposed.
|
|
239
|
+
if(r.state!=='running'||w.status!=='active'||r.epoch!==w.epoch){
|
|
240
|
+
if(r.late_result&&r.late_result!==json(a.result))throw Error('A2A_RESULT_CONFLICT');
|
|
241
|
+
this.db.prepare("UPDATE a2a_requests SET state='needs_review',late_result=?,drained_at=? WHERE id=?").run(json(a.result),this.now(),r.id);
|
|
242
|
+
this.audit(w.id,'late_result',{request_id:r.id});return {recorded:true,state:'needs_review',continued:false};
|
|
243
|
+
}
|
|
244
|
+
this.db.prepare("UPDATE a2a_requests SET state='completed',result=?,result_hash=?,drained_at=? WHERE id=?").run(json(a.result),fp,this.now(),r.id);
|
|
245
|
+
let child=null;
|
|
246
|
+
if(a.result.followup){
|
|
247
|
+
if(w.used_turns>=w.max_turns||w.used_requests>=w.max_requests)this.db.prepare("UPDATE a2a_grants SET status='waiting_input',reason='A2A_BUDGET_EXHAUSTED' WHERE id=?").run(w.id);
|
|
248
|
+
else child=this.insertRequest(w,node,a.result.followup,r.id);
|
|
249
|
+
}else this.db.prepare("UPDATE a2a_grants SET status='completed',reason=NULL WHERE id=?").run(w.id);
|
|
250
|
+
this.audit(w.id,'completed',{request_id:r.id,child_request_id:child});return {recorded:true,state:'completed',continued:!!child,child_request_id:child};
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
failed(node,a) {
|
|
254
|
+
shape(a,['request_id','claim','instance_id','code','model_calls']); const code=/^A2A_[A-Z_]{1,80}$/.test(a.code??'')?a.code:'A2A_EXECUTION_FAILED';
|
|
255
|
+
return tx(this.db,()=>{
|
|
256
|
+
const r=this.owned(node,a),w=this.get(r.grant_id);this.recordModels(r,a.model_calls);
|
|
257
|
+
if(r.result_hash||r.state==='needs_review'&&r.drained_at!==null)return {state:r.state,unchanged:true};
|
|
258
|
+
if(!activeRequests.has(r.state)&&r.state!=='needs_review')throw Error('A2A_EXECUTION_NOT_STARTED');
|
|
259
|
+
this.db.prepare("UPDATE a2a_requests SET state='needs_review',error=COALESCE(error,?),drained_at=? WHERE id=?").run(code,this.now(),r.id);
|
|
260
|
+
if(w.status==='active')this.db.prepare("UPDATE a2a_grants SET status='needs_review',reason=?,epoch=epoch+1 WHERE id=?").run(code,w.id);
|
|
261
|
+
this.audit(w.id,'drained_failure',{request_id:r.id,code});return {state:'needs_review',drained:true,retry:false};
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
stop(w,status,reason) {
|
|
265
|
+
this.db.prepare('UPDATE a2a_grants SET status=?,reason=?,epoch=epoch+1 WHERE id=?').run(status,reason,w.id);
|
|
266
|
+
for(const r of this.requests(w.id)) {
|
|
267
|
+
if(r.state==='running')this.db.prepare("UPDATE a2a_requests SET state='stopping',error=? WHERE id=?").run(reason,r.id);
|
|
268
|
+
else if(['queued','claimed'].includes(r.state))this.db.prepare('UPDATE a2a_requests SET state=?,claim=NULL,instance=NULL,epoch=NULL,lease_until=NULL,error=?,drained_at=? WHERE id=?')
|
|
269
|
+
.run(status==='paused'?'queued':'cancelled',reason,status==='paused'?null:this.now(),r.id);
|
|
270
|
+
}
|
|
271
|
+
this.audit(w.id,status,{reason});
|
|
272
|
+
}
|
|
273
|
+
control(node,a) {
|
|
274
|
+
shape(a,['grant_id','action','sources','authorization_quote','event_id']);human(node,a);
|
|
275
|
+
if(!['pause','resume','revoke'].includes(a.action))throw Error('A2A_CONTROL_INVALID');const fp=hash({node,...a});
|
|
276
|
+
return tx(this.db,()=>{
|
|
277
|
+
const old=this.db.prepare('SELECT * FROM a2a_events WHERE event_id=?').get(a.event_id);
|
|
278
|
+
if(old){if(old.fingerprint!==fp)throw Error('A2A_EVENT_CONFLICT');return JSON.parse(old.result);}
|
|
279
|
+
const w=this.get(a.grant_id);
|
|
280
|
+
if(a.action==='resume'){
|
|
281
|
+
this.current(w);if(w.status!=='paused')throw Error('A2A_RESUME_DENIED');
|
|
282
|
+
if(this.requests(w.id).some(r=>activeRequests.has(r.state)||r.state==='needs_review'))throw Error('A2A_DRAIN_OR_REVIEW_REQUIRED');
|
|
283
|
+
this.db.prepare("UPDATE a2a_grants SET status='active',reason=NULL,epoch=epoch+1 WHERE id=?").run(w.id);this.audit(w.id,'resumed');
|
|
284
|
+
}else{
|
|
285
|
+
if(!['active','paused','needs_review','waiting_input'].includes(w.status))throw Error('A2A_CONTROL_INVALID');
|
|
286
|
+
this.stop(w,a.action==='pause'?'paused':'revoked',a.action==='pause'?'A2A_USER_PAUSED':'A2A_USER_REVOKED');
|
|
287
|
+
}
|
|
288
|
+
const result={id:w.id,state:this.get(w.id).status,drained:!this.requests(w.id).some(r=>activeRequests.has(r.state)||r.state==='needs_review'&&r.drained_at===null),budget_reset:false};
|
|
289
|
+
this.db.prepare('INSERT INTO a2a_events VALUES (?,?,?)').run(a.event_id,fp,json(result));return result;
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
call(method,a,node) {
|
|
293
|
+
if(!['local','cloud'].includes(node))throw Error('AUTH_DENIED');
|
|
294
|
+
const methods={a2a_create:'create',a2a_start:'start',a2a_claim:'claim',a2a_begin:'begin',a2a_validate:'validate',a2a_reserve:'reserve',a2a_finish:'finish',a2a_failed:'failed',a2a_control:'control'};
|
|
295
|
+
if(method==='a2a_list'){shape(a,['task_id']);return this.list(a.task_id);}
|
|
296
|
+
if(!Object.hasOwn(methods,method))throw Error('METHOD_DENIED');return this[methods[method]](node,a);
|
|
297
|
+
}
|
|
298
|
+
}
|