agent-policy-kit 0.1.0 → 0.3.0

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/src/output.mjs ADDED
@@ -0,0 +1,108 @@
1
+ import {PRESETS} from './release.mjs';
2
+ const LABELS={chatgpt:'ChatGPT',claude:'Claude',kimi:'Kimi',gemini:'Gemini',grok:'Grok'};
3
+ const label=client=>LABELS[client]??'Tool';
4
+ const code=value=>typeof value==='string'&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(value)?value:'OPERATION_FAILED';
5
+ const PRESET_LABELS=Object.fromEntries(PRESETS.map(entry=>[entry.id,entry.label]));
6
+ const preset=value=>Object.hasOwn(PRESET_LABELS,value)?' · '+PRESET_LABELS[value]:'';
7
+ const NOTES={
8
+ 'chatgpt-native-precedence-limits':'Project and explicit client settings can override these defaults.',
9
+ 'claude-native-precedence-limits':'Project and explicit client settings can override these defaults.',
10
+ 'kimi-concurrency-guidance-only':'Kimi: the concurrency limit is guidance.',
11
+ 'kimi-model-pool-routing-guidance':'Kimi: the parent selects the model alias for each role.',
12
+ 'gemini-concurrency-guidance-only':'Gemini: the concurrency limit is guidance.',
13
+ 'gemini-per-role-effort-unsupported':'Gemini: native tiers do not support per-role effort.',
14
+ 'grok-per-role-effort-unsupported':'Grok: native agent settings do not support per-role effort.',
15
+ 'grok-native-precedence-limits':'Project and explicit client settings can override these defaults.',
16
+ 'kimi-catalog-alias-resolved':'Kimi: an existing matching model alias was selected.',
17
+ };
18
+ const REASONS={
19
+ OWNED_DRIFT:'Local edits prevent an update',
20
+ 'kimi-provisioned-models-required':'Required model aliases are missing',
21
+ 'native-home-override-unsupported':'The active client profile uses a nonstandard location',
22
+ 'client-not-selected':'This tool is not selected in the configuration',
23
+ 'claude-force-model-conflict':'A forced model conflicts with the selected roles',
24
+ 'kimi-supported-effort-required':'A selected alias does not declare the required effort support',
25
+ 'kimi-main-effort-conflict':'The requested effort would change the main model defaults',
26
+ 'kimi-thinking-disabled':'Thinking is disabled for a model that requires it',
27
+ 'kimi-mixed-native-default-effort':'A shared effort override conflicts with native-default roles',
28
+ 'kimi-catalog-alias-ambiguous':'More than one existing model alias matches',
29
+ 'kimi-resolved-model-avoided':'The matching alias is on the avoid list',
30
+ 'kimi-resolved-effort-conflict':'Roles sharing an alias request conflicting effort levels',
31
+ INSTALLATION_CONFLICT:'Installed preferences differ from this request',
32
+ POLICY_CONFLICT:'Saved preferences differ from this request',
33
+ RECOVERY_REQUIRED:'An interrupted transaction requires recovery',
34
+ INSTALL_LOCKED:'Another configuration operation holds the lock',
35
+ };
36
+ export const useJsonOutput=({isTTY,json=false}={})=>json||!isTTY;
37
+ function reason(value){const id=code(value);return (REASONS[id]??'Configuration could not be completed')+` (${id})`;}
38
+ function row(client,text,mark='✓'){return `${mark} ${label(client).padEnd(14)} ${text}`;}
39
+ function setup(result,{apply}){
40
+ const results=result.results??[],failed=results.some(r=>['error','prerequisite','invalid','timeout'].includes(r.status));
41
+ const changed=results.filter(r=>r.status==='configured');
42
+ const heading=failed?'Setup incomplete':result.status==='no_clients'?'No supported selected tools found':!apply?'Preview · no files changed':changed.length?'Configuration applied':'Already up to date';
43
+ const lines=[heading,''],missing=[],notes=new Set();
44
+ for(const r of results){
45
+ if(r.status==='not_selected')continue;
46
+ if(r.status==='not_found'){missing.push(label(r.client));continue;}
47
+ const warnings=r.warnings??r.plan?.warnings??[];
48
+ let text,mark='✓';
49
+ if(r.status==='configured')text='Configuration applied'+preset(r.appliedPreset);
50
+ else if(r.status==='unchanged'||r.status==='planned'&&r.plan?.files?.length===0)text='Already up to date'+preset(r.appliedPreset);
51
+ else if(r.status==='planned'){text='Would configure'+preset(r.targetPreset);mark='·';}
52
+ else if(r.status==='invalid'){text='Client executable identity could not be verified';mark='!';}
53
+ else if(r.status==='timeout'){text='Client detection timed out';mark='!';}
54
+ else {text=reason(r.error??warnings[0]);mark='!';}
55
+ lines.push(row(r.client,text,mark));
56
+ if(r.status==='prerequisite'&&r.appliedReleaseVersion&&/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(r.appliedReleaseVersion))lines.push(` Existing configuration retained · ${r.appliedReleaseVersion}${preset(r.appliedPreset)}`);
57
+ if(['configured','unchanged','planned'].includes(r.status))for(const warning of warnings)notes.add(NOTES[warning]??`Client note: ${code(warning)}`);
58
+ }
59
+ if(missing.length)lines.push(`Skipped: ${missing.join(', ')} — not installed.`);
60
+ if(changed.length)lines.push('',`Open a new session in ${changed.map(r=>label(r.client)).join(', ')} to load the changes.`);
61
+ if(results.some(r=>r.error==='OWNED_DRIFT'))lines.push('Review local edits before retrying; APK will not overwrite them.');
62
+ if(results.some(r=>(r.warnings??r.plan?.warnings??[]).includes('kimi-provisioned-models-required')))lines.push('Configure the selected model aliases in Kimi, then run the same command again.');
63
+ if(notes.size)lines.push('',...notes);
64
+ lines.push('Native configuration only; model execution was not checked.');
65
+ return lines;
66
+ }
67
+ function uninstall(result,{apply}){
68
+ const results=result.results??(result.client?[result]:[]);
69
+ const lines=[!apply?'Preview · no files changed':result.status==='partial'?'Removal incomplete':result.status==='not_installed'?'Nothing to remove':'Configuration removal',''];
70
+ for(const r of results){const bad=r.status==='error';lines.push(row(r.client,bad?reason(r.error):r.status==='unchanged'||r.files?.length===0?'Nothing to remove':apply?'Configuration removed':'Would remove',bad?'!':apply?'✓':'·'));}
71
+ return lines;
72
+ }
73
+ const setting=value=>typeof value==='string'&&/^[A-Za-z0-9][A-Za-z0-9 _.:@/\[\]-]{0,127}$/.test(value)?value:'native default';
74
+ function show(result){
75
+ const lines=['User configuration · subagents',''];
76
+ for(const[id,c]of Object.entries(result.clients??{})){
77
+ lines.push(`${label(id)}${c.status==='attention'?' · incomplete read':c.status==='not_configured'?' · no explicit subagent settings':''}`);
78
+ if(c.status!=='not_configured'){
79
+ if(c.defaults.enabled===false)lines.push(' Subagents explicitly disabled.');
80
+ lines.push(` Default model: ${setting(c.defaults.model)} · effort: ${setting(c.defaults.effort)}`);
81
+ lines.push(` Max concurrent: ${Number.isSafeInteger(c.concurrency.value)?c.concurrency.value:'not explicitly set'}${c.concurrency.kind==='guidance'?' (guidance)':' (native setting)'}`);
82
+ for(const role of c.roles)lines.push(` ${setting(role.name).padEnd(22)} ${setting(role.model)} · ${setting(role.effort)}${role.modelSelection==='guidance'?' (routing guidance)':role.modelSelection==='parent'?' (parent selects model)':''}${role.enabled===false?' (delegation disabled)':''}`);
83
+ for(const entry of c.pool)lines.push(` Pool: ${setting(entry.alias)} · ${setting(entry.effort)}${entry.configured?'':' · alias not provisioned'}`);
84
+ for(const[field,value]of Object.entries(c.overrides??{}))lines.push(` Override ${field}: ${typeof value==='boolean'?String(value):typeof value==='number'?value:setting(value)}`);
85
+ }
86
+ if(c.apk.status==='modified')lines.push(' APK-managed files have local edits; the values above come from current files.');
87
+ for(const warning of c.warnings)lines.push(` ! ${code(warning)}`);
88
+ lines.push('');
89
+ }
90
+ lines.push('User-level files only; project, managed and session settings may override them.','Native configuration only; model execution was not checked.');
91
+ return lines;
92
+ }
93
+ export function formatResult(command,result,{version='',apply=false}={}){
94
+ let lines;
95
+ if(result.error)lines=[`Operation failed (${code(result.error)})`];
96
+ else if(command==='setup'||command==='install')lines=setup(result,{apply});
97
+ else if(command==='uninstall')lines=uninstall(result,{apply});
98
+ else if(command==='show')lines=show(result);
99
+ else if(command==='init')lines=['Preferences created.'];
100
+ else if(command==='detect')lines=result.map(r=>row(r.client,r.status==='detected'?`Detected${typeof r.version==='string'&&/^[0-9A-Za-z.+-]{1,128}$/.test(r.version)?' · '+r.version:''}`:r.status==='not_found'?'Not installed':r.status==='timeout'?'Detection timed out':'Identity unverified',r.status==='detected'?'✓':r.status==='not_found'?'·':'!'));
101
+ else if(command==='doctor'){
102
+ lines=['Configuration check',''];
103
+ for(const[client,r]of Object.entries(result.clients??{})){const c=r.configuration;lines.push(row(client,c.status==='verified'?`Verified${preset(c.preset)}`:c.status==='not_configured'?'Not configured':reason(c.reason),c.status==='attention'?'!':c.status==='verified'?'✓':'·'));}
104
+ lines.push('Native configuration only; model execution was not checked.');
105
+ }else if(command==='release')lines=[`Configuration release ${/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(result.version)?result.version:''}${preset(result.preset)}`,'','Use setup --release to preview; add --apply to configure.'];
106
+ else lines=['Operation completed.'];
107
+ return [`Agent Policy Kit${/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(version)?' · '+version:''}`,'',...lines].join('\n')+'\n';
108
+ }
package/src/policy.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import catalog from '../models/catalog.json' with {type:'json'};
2
2
  import {ROLES,ROLE_IDS,selectedRoleIds} from './roles.mjs';
3
3
  export {ROLES} from './roles.mjs';
4
- export const CLIENTS = Object.freeze(['codex', 'claude', 'kimi', 'agy']);
4
+ export const CLIENTS = Object.freeze(['chatgpt', 'claude', 'kimi', 'gemini', 'grok']);
5
5
  export const rolePreference=(config,role)=>config.roles?.[role]??config[ROLES[role]];
6
6
  export const NATIVE_EFFORTS=Object.freeze(Object.fromEntries(CLIENTS.map(client=>[client,Object.freeze([...catalog.clients[client].efforts])])));
7
7
  const identifier = /^[A-Za-z0-9][A-Za-z0-9._:@/\[\]-]{0,127}$/;
@@ -21,12 +21,13 @@ export function validatePolicy(value) {
21
21
  object(value.clients,CLIENTS);
22
22
  if (!Object.keys(value.clients).length) invalid();
23
23
  for (const [client,config] of Object.entries(value.clients)) {
24
- object(config,['code','light','roles','avoidModels']);
24
+ object(config,['code','light','roles','avoidModels','maxConcurrent']);
25
+ if(config.maxConcurrent!==undefined&&(!Number.isInteger(config.maxConcurrent)||config.maxConcurrent<1||config.maxConcurrent>32))invalid();
25
26
  if(config.roles!==undefined)object(config.roles,Object.keys(ROLES));
26
27
  for (const selected of [config.code,config.light,...Object.values(config.roles??{})]) {
27
28
  object(selected,['model','effort']); model(selected.model);
28
29
  if (client === 'kimi' && selected.model === 'primary') invalid();
29
- if(client==='agy'&&!['pro','flash','flash_lite','inherit'].includes(selected.model))invalid();
30
+ if(client==='gemini'&&!['pro','flash','flash_lite','inherit'].includes(selected.model))invalid();
30
31
  if(selected.effort!==null){
31
32
  if(!NATIVE_EFFORTS[client].includes(selected.effort))invalid();
32
33
  const known=catalog.clients[client].models.find(model=>model.id===selected.model);
package/src/release.mjs CHANGED
@@ -4,7 +4,7 @@ import {validatePolicy} from './policy.mjs';
4
4
 
5
5
  export const PACKAGE_VERSION=JSON.parse(fs.readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
6
6
  const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
7
- export const PRESETS=Object.freeze([{id:'fast',label:'Fast & economical',description:'For small, well-defined tasks. Lighter models, with extra reasoning for review and tests.'},{id:'balanced',label:'Balanced',description:'Stronger coding and verification, lighter exploration and mechanical work.'},{id:'quality',label:'Quality first',description:'For demanding implementation and verification. Prioritizes capability over response time and usage.'}].map(Object.freeze));
7
+ export const PRESETS=Object.freeze([{id:'fast',label:'Light',description:'Light models for every role. Limits last longest.'},{id:'balanced',label:'Standard',description:'Stronger models for code, review, tests and docs. Fits most plans.'},{id:'quality',label:'Top-tier',description:'High-end models for most roles. Uses limits fastest.',topModels:Object.freeze({chatgpt:'gpt-6-astra',claude:'claude-fable-5-1',kimi:'kimi-code/k3.1-pro'})}].map(Object.freeze));
8
8
  export function presetPreferences(id='balanced'){
9
9
  if(!PRESETS.some(preset=>preset.id===id))throw Object.assign(new Error('Unknown preset.'),{code:'UNKNOWN_PRESET'});
10
10
  return validatePolicy(JSON.parse(fs.readFileSync(new URL(`../policies/${id}.json`,import.meta.url),'utf8')));
package/src/setup.mjs CHANGED
@@ -4,7 +4,7 @@ import { nativeHomeConflict } from './native.mjs';
4
4
  import { PACKAGE_VERSION } from './release.mjs';
5
5
  import { CLIENTS } from './policy.mjs';
6
6
 
7
- const ERRORS = new Set(['INVALID_PRESET','INVALID_RELEASE','LEGACY_RUNTIME_RECEIPT','INVALID_CLIENT','INVALID_POLICY','INVALID_JSON','INVALID_TOML','UNSUPPORTED_CONFIG','UNSUPPORTED_TOML_STRUCTURE','UNSUPPORTED_TOML_VALUE','CODEX_CAP_ALIAS_CONFLICT','OWNERSHIP_CONFLICT','INVALID_RECEIPT','OWNED_DRIFT','INSTALLATION_CONFLICT','POLICY_CONFLICT','UNSAFE_PATH','UNSAFE_FILE','STALE_PLAN','RECOVERY_REQUIRED','ROLLBACK_CONFLICT','INVALID_PLAN','PLATFORM_UNSUPPORTED','INSTALL_LOCKED','INSTALL_FAILED','EACCES','EPERM','ENOENT','ENOSPC','EIO','EROFS']);
7
+ const ERRORS = new Set(['INVALID_PRESET','INVALID_RELEASE','LEGACY_RUNTIME_RECEIPT','INVALID_CLIENT','INVALID_POLICY','INVALID_JSON','INVALID_TOML','UNSUPPORTED_CONFIG','UNSUPPORTED_TOML_STRUCTURE','UNSUPPORTED_TOML_VALUE','CHATGPT_CAP_ALIAS_CONFLICT','OWNERSHIP_CONFLICT','INVALID_RECEIPT','OWNED_DRIFT','INSTALLATION_CONFLICT','POLICY_CONFLICT','UNSAFE_PATH','UNSAFE_FILE','STALE_PLAN','RECOVERY_REQUIRED','ROLLBACK_CONFLICT','INVALID_PLAN','PLATFORM_UNSUPPORTED','INSTALL_LOCKED','INSTALL_FAILED','EACCES','EPERM','ENOENT','ENOSPC','EIO','EROFS']);
8
8
  const safeError = error => ERRORS.has(error?.code) ? error.code : 'SETUP_FAILED';
9
9
  function actions(client,warnings) {
10
10
  return warnings.map(code=>({client,code,automatable:false}));
package/src/share.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // Pure URL state codec, also embedded in the offline configuration page.
2
2
  const SHARE_BYTES=65536,SHARE_TOKEN=87384;
3
- const SHARE_VERSION=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
3
+ const SHARE_VERSION=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?$/;
4
4
  const SHARE_UNSAFE=new Set(['__proto__','constructor','prototype']);
5
5
  function invalidShare(){throw Object.assign(new Error('Invalid shared configuration link.'),{code:'INVALID_SHARE_LINK'});}
6
6
 
@@ -46,46 +46,67 @@ function shareRelease(release){
46
46
  }
47
47
  for(const preset of release.presets){
48
48
  shareRecord(preset);if(typeof preset.id!=='string'||!preset.id||preset.id==='custom'||SHARE_UNSAFE.has(preset.id)||presets.has(preset.id))invalidShare();
49
- shareRecord(shareRecord(preset.preferences).clients);presets.set(preset.id,preset);
49
+ shareRecord(shareRecord(preset.preferences).clients);
50
+ if(preset.topModels!==undefined&&Object.values(shareRecord(preset.topModels)).some(model=>typeof model!=='string'))invalidShare();
51
+ presets.set(preset.id,preset);
50
52
  }
51
53
  if(!presets.has(release.preset))invalidShare();
52
54
  return {clients,roles,presets,catalog};
53
55
  }
54
56
  function shareChoice(choice,id,metadata){
55
57
  shareRecord(choice,['model','effort']);
56
- if(typeof choice.model!=='string'||choice.model.length>128||(choice.effort!==null&&(id==='agy'||!metadata.catalog[id].efforts.includes(choice.effort))))invalidShare();
58
+ if(typeof choice.model!=='string'||choice.model.length>128||(choice.effort!==null&&(['gemini','grok'].includes(id)||!metadata.catalog[id].efforts.includes(choice.effort))))invalidShare();
57
59
  return {model:choice.model,effort:choice.effort};
58
60
  }
59
61
  function sharePayload(payload,release,metadata){
60
- shareRecord(payload,['v','release','roles','tools','scope','maxConcurrent']);
61
- if(payload.v!==1||typeof payload.release!=='string'||!SHARE_VERSION.test(payload.release))invalidShare();
62
- if(payload.release!==release.version)throw Object.assign(new Error('This link uses a different release.'),{code:'SHARE_RELEASE_MISMATCH'});
63
- if(!Number.isInteger(payload.maxConcurrent)||payload.maxConcurrent<1||payload.maxConcurrent>32)invalidShare();
62
+ shareRecord(payload);const legacy=payload.v===1;
63
+ if(!legacy&&payload.v!==2)invalidShare();
64
+ shareRecord(payload,legacy?['v','release','roles','tools','scope','maxConcurrent']:['v','release','roles','tools','scope']);
65
+ if(typeof payload.release!=='string'||payload.release.length>128||!SHARE_VERSION.test(payload.release))invalidShare();
66
+ if(legacy&&(!Number.isInteger(payload.maxConcurrent)||payload.maxConcurrent<1||payload.maxConcurrent>32))invalidShare();
67
+ if(payload.release!==release.version){
68
+ // Validate the wire shape without imposing today's models or preset values on
69
+ // an older release. Invalid links must never turn into navigation.
70
+ const identifier=value=>typeof value==='string'&&/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value);
71
+ if(!Array.isArray(payload.roles)||payload.roles.length>1000||payload.roles.some(role=>!identifier(role)))invalidShare();
72
+ const roles=shareList(payload.roles,payload.roles),ids=[];
73
+ if(!Array.isArray(payload.tools)||payload.tools.length>32)invalidShare();
74
+ for(const tool of payload.tools){
75
+ shareRecord(tool,legacy?['id','mode','base','choices']:['id','mode','base','choices','maxConcurrent']);if(!legacy&&(!Number.isInteger(tool.maxConcurrent)||tool.maxConcurrent<1||tool.maxConcurrent>32))invalidShare();if(!identifier(tool.id)||ids.includes(tool.id)||!identifier(tool.base)||(tool.mode!==null&&!identifier(tool.mode)))invalidShare();ids.push(tool.id);
76
+ shareRecord(tool.choices,roles);for(const role of roles){const choice=shareRecord(tool.choices[role],['model','effort']);if(typeof choice.model!=='string'||choice.model.length>128||(choice.effort!==null&&(typeof choice.effort!=='string'||choice.effort.length>32)))invalidShare();}
77
+ }
78
+ if(payload.scope!==null&&(typeof payload.scope!=='string'||(payload.scope==='all'?ids.length<2:!ids.includes(payload.scope))))invalidShare();
79
+ throw Object.assign(new Error('This link uses a different release.'),{code:'SHARE_RELEASE_MISMATCH',releaseVersion:payload.release});
80
+ }
64
81
  const roles=shareList(payload.roles,[...metadata.roles.keys()]);
65
82
  if(!Array.isArray(payload.tools)||payload.tools.length>metadata.clients.length)invalidShare();
66
83
  const selected=[];
67
84
  const tools=payload.tools.map(tool=>{
68
- shareRecord(tool,['id','mode','base','choices']);
85
+ shareRecord(tool,legacy?['id','mode','base','choices']:['id','mode','base','choices','maxConcurrent']);if(!legacy&&(!Number.isInteger(tool.maxConcurrent)||tool.maxConcurrent<1||tool.maxConcurrent>32))invalidShare();
69
86
  const {id,mode,base}=tool;
70
87
  if(!metadata.clients.includes(id)||selected.includes(id)||!metadata.presets.has(base)||(mode!==null&&mode!=='custom'&&!metadata.presets.has(mode)))invalidShare();
71
88
  selected.push(id);shareRecord(tool.choices,roles);
72
89
  const choices=Object.fromEntries(roles.map(role=>[role,shareChoice(tool.choices[role],id,metadata)]));
73
90
  if(mode!==null&&mode!=='custom'){
74
91
  if(mode!==base)invalidShare();
75
- const clients=metadata.presets.get(mode).preferences.clients;
92
+ const named=metadata.presets.get(mode),preset=named.preferences,clients=preset.clients;
93
+ if(!legacy&&tool.maxConcurrent!==(clients[id]?.maxConcurrent??preset.maxConcurrent))invalidShare();
76
94
  if(!Object.hasOwn(clients,id))invalidShare();
77
- const preferences=shareRecord(clients[id]);
95
+ const preferences=shareRecord(clients[id]),own=role=>preferences.roles&&Object.hasOwn(preferences.roles,role);
96
+ // A preset's optional top model replaces every shared code role that has no role-specific choice, or none of them.
97
+ const top=named.topModels&&Object.hasOwn(named.topModels,id)?named.topModels[id]:null;
98
+ const topRoles=roles.filter(role=>metadata.roles.get(role).kind==='code'&&!own(role)),topped=top!==null&&topRoles.some(role=>choices[role].model===top);
78
99
  for(const role of roles){
79
- const expected=preferences.roles&&Object.hasOwn(preferences.roles,role)?preferences.roles[role]:preferences[metadata.roles.get(role).kind];
80
- const choice=shareChoice(expected,id,metadata);
100
+ const expected=own(role)?preferences.roles[role]:preferences[metadata.roles.get(role).kind];
101
+ const choice=shareChoice(expected,id,metadata);if(topped&&topRoles.includes(role))choice.model=top;
81
102
  if(choice.model!==choices[role].model||choice.effort!==choices[role].effort)invalidShare();
82
103
  }
83
104
  }
84
- return {id,mode,base,choices};
105
+ return {id,mode,base,choices,...(legacy?{}:{maxConcurrent:tool.maxConcurrent})};
85
106
  });
86
107
  const scope=payload.scope;
87
108
  if(scope!==null&&(typeof scope!=='string'||(scope==='all'?tools.length<2:!selected.includes(scope))))invalidShare();
88
- return {v:1,release:payload.release,roles,tools,scope,maxConcurrent:payload.maxConcurrent};
109
+ return {v:payload.v,release:payload.release,roles,tools,scope,...(legacy?{maxConcurrent:payload.maxConcurrent}:{})};
89
110
  }
90
111
  function shareBase64(bytes){return btoa(Array.from(bytes,byte=>String.fromCharCode(byte)).join('')).replaceAll('+','-').replaceAll('/','_').replace(/=+$/,'');}
91
112
  function shareJson(text){
@@ -111,15 +132,16 @@ export function encodeFormState(snapshot,release){
111
132
  shareData(snapshot);shareRecord(snapshot);
112
133
  const metadata=shareRelease(release),state=shareRecord(snapshot.state),profiles=shareRecord(state.profiles),jobs=shareRecord(state.jobs);
113
134
  const roles=shareList(snapshot.helpers,[...metadata.roles.keys()]),selected=shareList(snapshot.pickedTools,metadata.clients);
135
+ const modern=Object.values(profiles).some(profile=>Object.hasOwn(profile,'maxConcurrent'));
114
136
  const tools=selected.map(id=>{
115
137
  if(!Object.hasOwn(profiles,id)||!Object.hasOwn(jobs,id))invalidShare();
116
138
  const profile=shareRecord(profiles[id]),choices=shareRecord(jobs[id]);
117
139
  if(typeof profile.custom!=='boolean'||(profile.modeSelected!==undefined&&typeof profile.modeSelected!=='boolean'))invalidShare();
118
- return {id,mode:profile.modeSelected===false?null:profile.custom?'custom':profile.presetId,base:profile.presetId,choices:Object.fromEntries(roles.map(role=>{
140
+ return {id,...(modern?{maxConcurrent:Object.hasOwn(profile,'maxConcurrent')?profile.maxConcurrent:state.maxConcurrent}:{}),mode:profile.modeSelected===false?null:profile.custom?'custom':profile.presetId,base:profile.presetId,choices:Object.fromEntries(roles.map(role=>{
119
141
  if(!Object.hasOwn(choices,role))invalidShare();return [role,shareChoice(choices[role],id,metadata)];
120
142
  }))};
121
143
  });
122
- const payload=sharePayload({v:1,release:release.version,roles,tools,scope:snapshot.selectedScope,maxConcurrent:state.maxConcurrent},release,metadata);
144
+ const payload=sharePayload({v:modern?2:1,release:release.version,roles,tools,scope:snapshot.selectedScope,...(modern?{}:{maxConcurrent:state.maxConcurrent})},release,metadata);
123
145
  if(!roles.length&&!tools.length)return '';
124
146
  const bytes=new TextEncoder().encode(JSON.stringify(payload));if(bytes.length>SHARE_BYTES)invalidShare();
125
147
  const token=shareBase64(bytes);if(token.length>SHARE_TOKEN)invalidShare();return '#setup='+token;
@@ -139,3 +161,12 @@ export function decodeFormState(fragment,release){
139
161
  return sharePayload(payload,release,shareRelease(release));
140
162
  }catch(error){if(error?.code==='INVALID_SHARE_LINK'||error?.code==='SHARE_RELEASE_MISMATCH')throw error;invalidShare();}
141
163
  }
164
+
165
+ export function archivedReleaseUrl(error,href,hostedReleases=[]){
166
+ if(error?.code!=='SHARE_RELEASE_MISMATCH'||typeof error.releaseVersion!=='string'||error.releaseVersion.length>128||!SHARE_VERSION.test(error.releaseVersion)||!Array.isArray(hostedReleases)||!hostedReleases.includes(error.releaseVersion))return null;
167
+ try{
168
+ const current=new URL(href);if(!['http:','https:'].includes(current.protocol)||current.username||current.password||current.pathname!=='/'||!current.hash.startsWith('#setup='))return null;
169
+ const target=new URL(`/v/${error.releaseVersion}/`,current.origin);target.hash=current.hash;
170
+ return target.origin===current.origin?target.href:null;
171
+ }catch{return null;}
172
+ }