@0x26/amp 0.5.1 → 0.5.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/README.md +12 -0
- package/dist/index.js +9 -8
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -51,3 +51,15 @@ amp login --install-skill --skill-dir ~/.codex/skills/amp-cli
|
|
|
51
51
|
The default skill destination is Claude Code. Use `--skill-dir` for any agent's
|
|
52
52
|
skill directory. Existing hand-edited skill files are preserved. Start a new
|
|
53
53
|
agent session after installing the skill.
|
|
54
|
+
|
|
55
|
+
Ask answers include numbered sources and limitations. When the workspace has
|
|
56
|
+
evidence links configured, minute sources include a URL to the supporting
|
|
57
|
+
entry. “Preview unavailable” keeps the original source reference without a link.
|
|
58
|
+
Use `amp --agent ask "<question>"` for structured evidence and preview metadata.
|
|
59
|
+
|
|
60
|
+
Ask uses your signed-in account for “me” and your computer's timezone for “today”.
|
|
61
|
+
Override the timezone with `amp ask --timezone America/Los_Angeles "My activity today"`.
|
|
62
|
+
Your workspace needs an Ask service that supports timezone context. Sources and
|
|
63
|
+
available evidence URLs appear below human-readable answers; structured output
|
|
64
|
+
retains the evidence metadata. A source can lack a preview when no supporting
|
|
65
|
+
minute entry is available.
|
package/dist/index.js
CHANGED
|
@@ -13,7 +13,7 @@ Preview only; use --json or --out <file> for all returned data.`:"")}var current
|
|
|
13
13
|
`)?err.body:`${err.body}
|
|
14
14
|
`)):err instanceof NotLoggedInError?process.stderr.write(`${err.message}
|
|
15
15
|
`):process.stderr.write(`${err instanceof Error?err.message:String(err)}
|
|
16
|
-
`),process.exitCode=1}var DoorRefusalError,init_http=__esm({"src/http.ts"(){"use strict";init_experience(),init_brand(),init_credentials(),init_machine(),init_env_customer(),init_session(),init_request_credential(),DoorRefusalError=class extends Error{constructor(status,body){super(`door refused (HTTP ${status})`),this.status=status,this.body=body}}}});init_terminal();var CLI_VERSION="0.5.
|
|
16
|
+
`),process.exitCode=1}var DoorRefusalError,init_http=__esm({"src/http.ts"(){"use strict";init_experience(),init_brand(),init_credentials(),init_machine(),init_env_customer(),init_session(),init_request_credential(),DoorRefusalError=class extends Error{constructor(status,body){super(`door refused (HTTP ${status})`),this.status=status,this.body=body}}}});init_terminal();var CLI_VERSION="0.5.2";init_brand();init_config();init_credentials();init_lock();init_experience();init_brand();init_brand();init_workos();init_credentials();init_env_customer();init_config();init_brand();var STAMP_PREFIX="<!-- amp-managed skill \xB7 amp ";function bundledSkillPath(){return resolve(dirname3(fileURLToPath(import.meta.url)),"..","skill","SKILL.md")}function bundledSkill(){let p=bundledSkillPath();if(!existsSync3(p))throw new Error("Bundled skill missing. Reinstall the CLI package.");return readFileSync3(p,"utf8")}function defaultInstallPath(){return join3(homedir3(),".claude","skills","amp-cli","SKILL.md")}function stamped(text){return`${STAMP_PREFIX}${CLI_VERSION} \u2014 bundled customer skill; remove this stamp to preserve manual edits -->
|
|
17
17
|
${text}`}function isAmpManaged(text){return text.startsWith(STAMP_PREFIX)}function installSkill(target=defaultInstallPath()){let next=stamped(bundledSkill());if(existsSync3(target)){let current2=readFileSync3(target,"utf8");return isAmpManaged(current2)?(current2===next||writeFileSync3(target,next),"refreshed"):"kept-hand-edited"}return mkdirSync3(dirname3(target),{recursive:!0}),writeFileSync3(target,next),"installed"}var HTML_CONTENT_TYPE="text/html; charset=utf-8",SUCCESS_HTML=`<!doctype html>
|
|
18
18
|
<html lang="en">
|
|
19
19
|
<head>
|
|
@@ -97,23 +97,24 @@ Workspace: ${profile2?.name??"default"} \u2192 ${profile2?.store_url??bundle().m
|
|
|
97
97
|
`)}async function runSqlAuto(sql,opts){let toJob=async()=>{let res2=await runSqlJob(sql,{budgetMs:opts.budgetMs});return warnIfPartial(res2),res2};if(opts.job)return toJob();let res;try{res=await runSqlSync(sql,{limit:opts.limit,timeoutMs:opts.timeoutMs})}catch(err){if(err instanceof DoorRefusalError&&err.status===403&&machineConfigFromEnv())return process.stderr.write(`sync SQL door refused this machine credential; using the job lane\u2026
|
|
98
98
|
`),toJob();throw err}return res.truncated&&opts.limit===void 0?(progress(`Retrieving the complete query result\u2026
|
|
99
99
|
`),toJob()):(res.truncated&&opts.limit!==void 0&&progress(`(result cut at your --limit ${opts.limit}; raise it or use --job for more)
|
|
100
|
-
`),warnIfPartial(res,opts.limit!==void 0),{rows:res.rows??[],rowCount:res.rowCount,truncated:res.truncated})}async function sqlRun(statement,opts){try{readContext();for(let[flag,value,max]of[["limit",opts.limit,1e4],["timeout-ms",opts.timeoutMs,2147483647],["budget-ms",opts.budgetMs,28e4]])if(value!==void 0&&(!/^\d+$/.test(value)||Number(value)<1||Number(value)>max))throw new CliError("INVALID_ARGUMENT",`--${flag} must be a whole number between 1 and ${max}.`);let res=await runSqlAuto(statement,{limit:opts.limit?Number(opts.limit):void 0,timeoutMs:opts.timeoutMs?Number(opts.timeoutMs):void 0,budgetMs:opts.budgetMs?Number(opts.budgetMs):void 0,job:opts.job});emit({rowCount:res.rowCount??res.rows.length,truncated:res.truncated??!1,rows:res.rows},opts,void 0,{row_count:res.rowCount??res.rows.length,truncated:!!res.truncated||(res.rowCount??res.rows.length)>=1e5,...res.truncated||(res.rowCount??res.rows.length)>=1e5?{next_action:"Narrow the query by time range or filters; raise an explicit --limit or use --job where appropriate."}:{}})}catch(err){reportError(err)}}async function sqlJobFetch(jobId,opts){try{readContext();let res=await drainSqlJob(jobId);warnIfPartial(res),emit({rowCount:res.rowCount??res.rows.length,truncated:res.truncated??!1,rows:res.rows},opts,void 0,{row_count:res.rowCount??res.rows.length,truncated:!!res.truncated||(res.rowCount??res.rows.length)>=1e5,...res.truncated||(res.rowCount??res.rows.length)>=1e5?{next_action:"Narrow the query by time range or filters; raise an explicit --limit or use --job where appropriate."}:{}})}catch(err){reportError(err)}}function registerSql(program2){program2.command("sql").description("Run a read-only query against your workspace").argument("[statement]","one SELECT/WITH statement").option("--limit <n>","maximum rows for a quick query (default 1000, max 10000)").option("--timeout-ms <n>","time limit for a quick query in milliseconds").option("--budget-ms <n>","time limit for a background query in milliseconds (default 240000, max 280000)").option("--job","run in the background and wait for results").option("--json","compact JSON to stdout").option("--out <file>","write the full result to a file").action(async(statement,opts)=>{if(!statement){reportError(new CliError("INVALID_ARGUMENT","Provide a SELECT or WITH statement, or resume a query with sql job <id>.",!1,"amp sql --help"));return}await sqlRun(statement,opts)}).command("job <sql-job-id>").description("Resume a query and retrieve its results").option("--json","compact JSON to stdout").option("--out <file>","write the full result to a file").action(async(jobId,opts)=>{await sqlJobFetch(jobId,opts)})}init_terminal();init_experience();init_brand();init_config();init_machine();init_request_credential();init_session();var defaults={fetch:(...args)=>fetch(...args),token:ensureFreshJwt,store:()=>{let selected=process.env.AMP_MCP_URL??activeProfile()?.store_url;if(!selected)throw new CliError("ASK_FAILED","Ask requires a selected tenant profile. Run amp login --store <url> --name <profile>.");return selected.replace(/\/mcp\/?$/,"")},stdout:text=>process.stdout.write(text),stderr:text=>process.stderr.write(text),uuid:randomUUID},object=value=>!!value&&typeof value=="object"&&!Array.isArray(value),validId=(value,prefix)=>typeof value=="string"&&new RegExp(`^${prefix}_[A-Za-z0-9_-]{1,128}$`).test(value)&&!/[\r\n]/.test(value),terminal=new Set(["completed","failed","cancelled","interrupted"]),statuses=new Set(["idle","active","cancelling","interrupted"]),invalid=()=>new Error("Invalid Ask response.");function origin(input,allowLocal){if(typeof input!="string"||input.trim()!==input||/[\s\\]/.test(input))throw new CliError("ASK_FAILED","Invalid Ask endpoint.");let url;try{url=new URL(input)}catch{throw new CliError("ASK_FAILED","Invalid Ask endpoint.")}if(url.username||url.password||url.search||url.hash||url.pathname!=="/"||url.protocol!=="https:"&&!(allowLocal&&url.protocol==="http:"&&loopback(url)))throw new CliError("ASK_FAILED","Ask endpoints require HTTPS origins; HTTP is allowed only for an explicitly selected local store.");return url}function loopback(url){return["localhost","127.0.0.1","[::1]"].includes(url.hostname)}function tokenOrg(token){try{if(!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?![\s\S])/.test(token))throw invalid();let claims=JSON.parse(Buffer.from(token.split(".")[1],"base64url").toString("utf8"));if(!object(claims)||typeof claims.sub!="string"||!claims.sub.startsWith("user_")||typeof claims.org_id!="string"||!/^org_[A-Za-z0-9]+(?![\s\S])/.test(claims.org_id)||typeof claims.exp!="number"||!Number.isFinite(claims.exp)||claims.exp*1e3<=Date.now()||claims.act!==void 0||claims.impersonator!==void 0||claims.nbf!==void 0&&(typeof claims.nbf!="number"||!Number.isFinite(claims.nbf)||claims.nbf*1e3>Date.now()))throw invalid();return claims.org_id}catch{throw new CliError("ASK_FAILED","Ask requires a valid, unexpired human session. Run amp login.")}}function answer(value){if(!object(value)||typeof value.text!="string"||!Array.isArray(value.evidence)||!Array.isArray(value.limitations)||!value.limitations.every(v=>typeof v=="string"))throw invalid();return value}function
|
|
100
|
+
`),warnIfPartial(res,opts.limit!==void 0),{rows:res.rows??[],rowCount:res.rowCount,truncated:res.truncated})}async function sqlRun(statement,opts){try{readContext();for(let[flag,value,max]of[["limit",opts.limit,1e4],["timeout-ms",opts.timeoutMs,2147483647],["budget-ms",opts.budgetMs,28e4]])if(value!==void 0&&(!/^\d+$/.test(value)||Number(value)<1||Number(value)>max))throw new CliError("INVALID_ARGUMENT",`--${flag} must be a whole number between 1 and ${max}.`);let res=await runSqlAuto(statement,{limit:opts.limit?Number(opts.limit):void 0,timeoutMs:opts.timeoutMs?Number(opts.timeoutMs):void 0,budgetMs:opts.budgetMs?Number(opts.budgetMs):void 0,job:opts.job});emit({rowCount:res.rowCount??res.rows.length,truncated:res.truncated??!1,rows:res.rows},opts,void 0,{row_count:res.rowCount??res.rows.length,truncated:!!res.truncated||(res.rowCount??res.rows.length)>=1e5,...res.truncated||(res.rowCount??res.rows.length)>=1e5?{next_action:"Narrow the query by time range or filters; raise an explicit --limit or use --job where appropriate."}:{}})}catch(err){reportError(err)}}async function sqlJobFetch(jobId,opts){try{readContext();let res=await drainSqlJob(jobId);warnIfPartial(res),emit({rowCount:res.rowCount??res.rows.length,truncated:res.truncated??!1,rows:res.rows},opts,void 0,{row_count:res.rowCount??res.rows.length,truncated:!!res.truncated||(res.rowCount??res.rows.length)>=1e5,...res.truncated||(res.rowCount??res.rows.length)>=1e5?{next_action:"Narrow the query by time range or filters; raise an explicit --limit or use --job where appropriate."}:{}})}catch(err){reportError(err)}}function registerSql(program2){program2.command("sql").description("Run a read-only query against your workspace").argument("[statement]","one SELECT/WITH statement").option("--limit <n>","maximum rows for a quick query (default 1000, max 10000)").option("--timeout-ms <n>","time limit for a quick query in milliseconds").option("--budget-ms <n>","time limit for a background query in milliseconds (default 240000, max 280000)").option("--job","run in the background and wait for results").option("--json","compact JSON to stdout").option("--out <file>","write the full result to a file").action(async(statement,opts)=>{if(!statement){reportError(new CliError("INVALID_ARGUMENT","Provide a SELECT or WITH statement, or resume a query with sql job <id>.",!1,"amp sql --help"));return}await sqlRun(statement,opts)}).command("job <sql-job-id>").description("Resume a query and retrieve its results").option("--json","compact JSON to stdout").option("--out <file>","write the full result to a file").action(async(jobId,opts)=>{await sqlJobFetch(jobId,opts)})}init_terminal();init_experience();init_brand();init_config();init_machine();init_request_credential();init_session();var defaults={timezone:()=>Intl.DateTimeFormat().resolvedOptions().timeZone,fetch:(...args)=>fetch(...args),token:ensureFreshJwt,store:()=>{let selected=process.env.AMP_MCP_URL??activeProfile()?.store_url;if(!selected)throw new CliError("ASK_FAILED","Ask requires a selected tenant profile. Run amp login --store <url> --name <profile>.");return selected.replace(/\/mcp\/?$/,"")},stdout:text=>process.stdout.write(text),stderr:text=>process.stderr.write(text),uuid:randomUUID},object=value=>!!value&&typeof value=="object"&&!Array.isArray(value),validId=(value,prefix)=>typeof value=="string"&&new RegExp(`^${prefix}_[A-Za-z0-9_-]{1,128}$`).test(value)&&!/[\r\n]/.test(value),terminal=new Set(["completed","failed","cancelled","interrupted"]),statuses=new Set(["idle","active","cancelling","interrupted"]),invalid=()=>new Error("Invalid Ask response.");function origin(input,allowLocal){if(typeof input!="string"||input.trim()!==input||/[\s\\]/.test(input))throw new CliError("ASK_FAILED","Invalid Ask endpoint.");let url;try{url=new URL(input)}catch{throw new CliError("ASK_FAILED","Invalid Ask endpoint.")}if(url.username||url.password||url.search||url.hash||url.pathname!=="/"||url.protocol!=="https:"&&!(allowLocal&&url.protocol==="http:"&&loopback(url)))throw new CliError("ASK_FAILED","Ask endpoints require HTTPS origins; HTTP is allowed only for an explicitly selected local store.");return url}function loopback(url){return["localhost","127.0.0.1","[::1]"].includes(url.hostname)}function tokenOrg(token){try{if(!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?![\s\S])/.test(token))throw invalid();let claims=JSON.parse(Buffer.from(token.split(".")[1],"base64url").toString("utf8"));if(!object(claims)||typeof claims.sub!="string"||!claims.sub.startsWith("user_")||typeof claims.org_id!="string"||!/^org_[A-Za-z0-9]+(?![\s\S])/.test(claims.org_id)||typeof claims.exp!="number"||!Number.isFinite(claims.exp)||claims.exp*1e3<=Date.now()||claims.act!==void 0||claims.impersonator!==void 0||claims.nbf!==void 0&&(typeof claims.nbf!="number"||!Number.isFinite(claims.nbf)||claims.nbf*1e3>Date.now()))throw invalid();return claims.org_id}catch{throw new CliError("ASK_FAILED","Ask requires a valid, unexpired human session. Run amp login.")}}function answer(value){if(!object(value)||typeof value.text!="string"||!Array.isArray(value.evidence)||!Array.isArray(value.limitations)||!value.limitations.every(v=>typeof v=="string"))throw invalid();return value}function evidenceDestination(url,type,id){let encoded=encodeURIComponent(id);if(type==="observation"&&/^\/people\/[^/]+\/day\/\d{4}-\d{2}-\d{2}$/.test(url.pathname)){let keys=[...url.searchParams.keys()];return keys.length===1&&["minute","stream"].includes(keys[0])&&url.searchParams.get(keys[0])===id}return url.search?!1:type==="process"?url.pathname===`/processes/${encoded}`:type==="workflow_run"?url.pathname===`/runs/${encoded}`:type==="process_instance"&&/^\/processes\/[^/]+\/instances\/[^/]+$/.test(url.pathname)&&url.pathname.endsWith(`/instances/${encoded}`)}function formatAskAnswer(value){let clean2=text=>text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,""),lines=[clean2(value.text)];return value.evidence.length&&(lines.push("","Sources"),value.evidence.forEach((ref,index)=>{if(!(!object(ref)||typeof ref.object_type!="string"||typeof ref.object_id!="string"||typeof ref.description!="string"))if(lines.push(`[${index+1}] ${clean2(ref.description)} (${clean2(ref.object_type)}: ${clean2(ref.object_id)})`),object(ref.preview)&&ref.preview.status==="available"&&typeof ref.preview.url=="string")try{let url=new URL(ref.preview.url);!/[\s\x00-\x1f\x7f-\x9f]/.test(ref.preview.url)&&!url.username&&!url.password&&!url.hash&&(url.protocol==="https:"||url.protocol==="http:"&&loopback(url))&&evidenceDestination(url,ref.object_type,ref.object_id)&&lines.push(` Open evidence: ${url.toString()}`)}catch{}else object(ref.preview)&&ref.preview.status==="unavailable"&&lines.push(" Preview unavailable")})),value.limitations.length&&lines.push("","Limitations",...value.limitations.map(item=>`- ${clean2(item)}`)),`${lines.join(`
|
|
101
|
+
`)}
|
|
102
|
+
`}function snapshot(value,conversation){if(!object(value)||!object(value.conversation)||value.conversation.id!==conversation||typeof value.status!="string"||!statuses.has(value.status)||value.active_request_id!==null&&!validId(value.active_request_id,"req")||!object(value.transcript)||value.transcript.conversation_id!==conversation||value.transcript.version!==1||!Array.isArray(value.transcript.entries))throw invalid();for(let entry of value.transcript.entries){if(!object(entry)||!validId(entry.request_id,"req")||entry.outcome!==void 0&&(typeof entry.outcome!="string"||!terminal.has(entry.outcome)))throw invalid();entry.outcome==="completed"&&answer(entry.answer)}return value}async function readChunk(reader,signal,timeout=6e4){let timer,abort;try{return await Promise.race([reader.read(),new Promise((_,reject)=>{abort=()=>reject(new Error("Ask connection interrupted.")),timer=setTimeout(()=>reject(new Error("Ask connection timed out.")),timeout),signal.addEventListener("abort",abort,{once:!0}),signal.aborted&&abort()})])}finally{clearTimeout(timer),abort&&signal.removeEventListener("abort",abort)}}async function jsonBody(response,signal,limit){if(!response.body)throw invalid();let reader=response.body.getReader(),chunks=[],size=0,deadline=Date.now()+3e4;try{for(;;){let{done,value}=await readChunk(reader,signal,Math.max(1,deadline-Date.now()));if(done)break;if(size+=value.byteLength,size>limit)throw new CliError("ASK_FAILED","Ask response exceeds the byte limit.");chunks.push(value)}try{return JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{throw invalid()}}finally{reader.cancel().catch(()=>{}),reader.releaseLock()}}async function events(response,conversation,request,io,signal){if(!response.headers.get("content-type")?.toLowerCase().startsWith("text/event-stream")||!response.body)throw invalid();let reader=response.body.getReader(),decoder=new TextDecoder("utf-8",{fatal:!0}),pending="",frameBytes=0,data=[],eventType="",sequence=-1;try{for(;;){let{done,value}=await readChunk(reader,signal);if(done)throw new CliError("ASK_FAILED","Ask event stream disconnected.");for(let offset=0;offset<value.length;offset+=4096){pending+=decoder.decode(value.subarray(offset,offset+4096),{stream:!0});let newline;for(;(newline=pending.indexOf(`
|
|
101
103
|
`))>=0;){let line=pending.slice(0,newline);if(pending=pending.slice(newline+1),frameBytes+=Buffer.byteLength(line)+1,frameBytes>65536)throw new CliError("ASK_FAILED","Ask event exceeds the byte limit.");if(line.endsWith("\r")&&(line=line.slice(0,-1)),line===""){if(data.length){let event;try{event=JSON.parse(data.join(`
|
|
102
104
|
`))}catch{throw invalid()}if(!object(event)||event.conversation_id!==conversation||event.request_id!==request||typeof event.sequence!="number"||!Number.isSafeInteger(event.sequence)||event.sequence<=sequence||event.type!==eventType)throw invalid();switch(sequence=event.sequence,event.type){case"progress":if(typeof event.message!="string")throw invalid();let message=event.message.replace(/[\x00-\x1f\x7f-\x9f]/g," ").slice(0,1e3);io.progress?io.progress(message):io.stderr(`${message}
|
|
103
|
-
`);break;case"answer_delta":if(typeof event.text!="string")throw invalid();break;case"status":if(typeof event.status!="string"||!statuses.has(event.status))throw invalid();if(event.status==="idle"||event.status==="interrupted")return;break;case"completed":answer(event.answer);return;case"failed":case"cancelled":return;default:throw invalid()}}frameBytes=0,data=[],eventType=""}else if(line.startsWith("data:"))data.push(line.slice(5).replace(/^ /,""));else if(line.startsWith("event:"))eventType=line.slice(6).replace(/^ /,"");else if(!line.startsWith(":")&&!line.startsWith("id:")&&!line.startsWith("retry:"))throw invalid()}if(frameBytes+Buffer.byteLength(pending)>65536)throw new CliError("ASK_FAILED","Ask event exceeds the byte limit.")}}}finally{reader.cancel().catch(()=>{}),reader.releaseLock()}}async function ask(question,options,injected={}){if(requestCredentialConfigured()||machineConfigFromEnv())throw new CliError("ASK_FAILED","Ask requires a saved human session; machine and request credentials cannot invoke Ask.");if(options.watch&&options.cancel||(options.watch||options.cancel)&&question!==void 0||(options.watch||options.cancel)&&!options.conversation||options.idempotencyKey!==void 0&&(options.watch||options.cancel)||options.conversation!==void 0&&!validId(options.conversation,"conv"))throw new CliError("ASK_FAILED","Use a question, --watch, or --cancel. Watch/cancel require --conversation conv_<id>.");if(!options.watch&&!options.cancel&&(typeof question!="string"||!question.trim()||Buffer.byteLength(question)>32768))throw new CliError("ASK_FAILED","Ask requires a nonempty question of at most 32768 UTF-8 bytes.");if(options.idempotencyKey!==void 0&&(!/^[\x21-\x7e]{1,128}$/.test(options.idempotencyKey)||/[\r\n]/.test(options.idempotencyKey)))throw new CliError("ASK_FAILED","Invalid idempotency key.");let io={...defaults,...injected};experience().quiet&&(io.stderr=()=>{});let structured=data=>`${JSON.stringify(experience().agent?envelope(data):data)}
|
|
105
|
+
`);break;case"answer_delta":if(typeof event.text!="string")throw invalid();break;case"status":if(typeof event.status!="string"||!statuses.has(event.status))throw invalid();if(event.status==="idle"||event.status==="interrupted")return;break;case"completed":answer(event.answer);return;case"failed":return object(event.error)&&["unsupported_answer","evidence_unavailable"].includes(String(event.error.code))?String(event.error.code):void 0;case"cancelled":return;default:throw invalid()}}frameBytes=0,data=[],eventType=""}else if(line.startsWith("data:"))data.push(line.slice(5).replace(/^ /,""));else if(line.startsWith("event:"))eventType=line.slice(6).replace(/^ /,"");else if(!line.startsWith(":")&&!line.startsWith("id:")&&!line.startsWith("retry:"))throw invalid()}if(frameBytes+Buffer.byteLength(pending)>65536)throw new CliError("ASK_FAILED","Ask event exceeds the byte limit.")}}}finally{reader.cancel().catch(()=>{}),reader.releaseLock()}}async function ask(question,options,injected={}){if(requestCredentialConfigured()||machineConfigFromEnv())throw new CliError("ASK_FAILED","Ask requires a saved human session; machine and request credentials cannot invoke Ask.");if(options.watch&&options.cancel||(options.watch||options.cancel)&&question!==void 0||(options.watch||options.cancel)&&!options.conversation||options.idempotencyKey!==void 0&&(options.watch||options.cancel)||options.conversation!==void 0&&!validId(options.conversation,"conv"))throw new CliError("ASK_FAILED","Use a question, --watch, or --cancel. Watch/cancel require --conversation conv_<id>.");if(!options.watch&&!options.cancel&&(typeof question!="string"||!question.trim()||Buffer.byteLength(question)>32768))throw new CliError("ASK_FAILED","Ask requires a nonempty question of at most 32768 UTF-8 bytes.");if(options.idempotencyKey!==void 0&&(!/^[\x21-\x7e]{1,128}$/.test(options.idempotencyKey)||/[\r\n]/.test(options.idempotencyKey)))throw new CliError("ASK_FAILED","Invalid idempotency key.");let io={...defaults,...injected};experience().quiet&&(io.stderr=()=>{});let structured=data=>`${JSON.stringify(experience().agent?envelope(data):data)}
|
|
104
106
|
`,machineOutput=options.json||experience().json||experience().agent,interactive=!machineOutput&&!experience().quiet&&process.env.TERM!=="dumb"&&(io.interactive??(!!process.stderr.isTTY&&!!process.stdout.isTTY)),status=interactive?askProgress(io.stderr,{color:colorEnabled(process.env,!!process.stderr.isTTY)}):void 0,lastStage="";io.progress=message=>{status?status.update(message):message!==lastStage&&(io.stderr(`${message}
|
|
105
107
|
`),lastStage=message)};let submissionKey,aborter=new AbortController,onAbort=()=>aborter.abort();io.signal?.addEventListener("abort",onAbort,{once:!0}),io.signal?.aborted&&aborter.abort();let conversation=options.conversation;try{let firstToken=await io.token(),org=tokenOrg(firstToken),store=origin(io.store(),!0),request=async(url,method="GET",body,key,stream=!1)=>{let token=await io.token();if(tokenOrg(token)!==org)throw new CliError("ASK_FAILED","Human session changed tenant; refusing Ask request.");let timeout=setTimeout(()=>aborter.abort(),15e3),response;try{response=await io.fetch(url,{method,redirect:"error",signal:aborter.signal,headers:{Authorization:`Bearer ${token}`,Accept:stream?"text/event-stream":"application/json",...body===void 0?{}:{"Content-Type":"application/json"},...key?{"Idempotency-Key":key}:{}},...body===void 0?{}:{body:JSON.stringify(body)}})}catch{throw new CliError("ASK_FAILED","Ask connection unavailable or interrupted.")}finally{clearTimeout(timeout)}if(response.redirected||response.status>=300&&response.status<400)throw response.body?.cancel().catch(()=>{}),new CliError("ASK_FAILED","Ask redirects are forbidden.");if(!response.ok)throw response.body?.cancel().catch(()=>{}),response.status!==409?httpError(response.status):response.status===409?new CliError("ASK_FAILED","Ask conflict (409): conversation_busy or idempotency_conflict; watch the existing conversation or retry the original input/key."):response.status===401?new CliError("ASK_FAILED","Ask authentication expired or revoked. Run amp login, then reattach."):new CliError("ASK_FAILED",`Ask request refused (HTTP ${response.status}).`);return response},config=await jsonBody(await request(`${store.origin}/v1/ask/config`),aborter.signal,65536);if(!object(config)||config.org_id!==org||config.protocol_version!==1)throw new CliError("ASK_FAILED","Ask discovery does not match this session's tenant/protocol.");let endpoint=origin(config.endpoint,loopback(store)).origin,route=()=>`${endpoint}/v1/conversations/${conversation}`,requestId;if(options.cancel){let response=await request(`${route()}/cancel`,"POST",{});if(response.status!==202)throw invalid();let cancelled=await jsonBody(response,aborter.signal,65536);if(!object(cancelled)||cancelled.request_id!==null&&!validId(cancelled.request_id,"req"))throw invalid();status?.stop(),machineOutput?io.stdout(structured({conversation_id:conversation,...cancelled})):io.stderr(`Cancellation requested for ${conversation}; conversation history is preserved.
|
|
106
108
|
`);return}if(!options.watch){let key=options.idempotencyKey??io.uuid();submissionKey=key,interactive||io.stderr(`Idempotency key: ${key}
|
|
107
|
-
`);let response=await request(`${endpoint}/v1/ask`,"POST",{question,...conversation?{conversation_id:conversation}:{}},key);if(response.status!==202)throw invalid();let accepted=await jsonBody(response,aborter.signal,65536);if(!object(accepted)||!validId(accepted.conversation_id,"conv")||!validId(accepted.request_id,"req")||conversation&&accepted.conversation_id!==conversation)throw invalid();conversation=accepted.conversation_id,requestId=accepted.request_id}interactive||io.stderr(`Conversation: ${conversation}${requestId?` \xB7 Request: ${requestId}`:""}
|
|
108
|
-
`);let get=async()=>snapshot(await jsonBody(await request(route()),aborter.signal,4259840),conversation),view=await get();if(requestId??=view.active_request_id??view.transcript.entries.at(-1)?.request_id,!requestId)throw new CliError("ASK_FAILED","Conversation has no saved question.");let find=()=>view.transcript.entries.find(entry2=>entry2.request_id===requestId);find()?.outcome||(await events(await request(`${route()}/events`,"GET",void 0,void 0,!0),conversation,requestId,io,aborter.signal),view=await get());let entry=find();if(!entry?.outcome)throw new CliError("ASK_FAILED","Answer is not persisted yet; reattach to check current status.");if(entry.outcome!=="completed")throw new CliError("ASK_FAILED",`Ask request ${entry.outcome}; conversation history is preserved.`);let finalAnswer=answer(entry.answer);status?.stop(),interactive&&io.stdout(`
|
|
109
|
+
`);let requestTimezone;try{let detected=options.timezone??io.timezone?.();if(detected){if(detected.length>100||!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+.-]+)*(?![\s\S])/.test(detected))throw new Error;requestTimezone=new Intl.DateTimeFormat("en-US",{timeZone:detected}).resolvedOptions().timeZone}else if(options.timezone!==void 0)throw new Error}catch{if(options.timezone!==void 0)throw new CliError("ASK_FAILED","Use a valid IANA timezone, such as America/Los_Angeles.")}let response=await request(`${endpoint}/v1/ask`,"POST",{question,...requestTimezone?{timezone:requestTimezone}:{},...conversation?{conversation_id:conversation}:{}},key);if(response.status!==202)throw invalid();let accepted=await jsonBody(response,aborter.signal,65536);if(!object(accepted)||!validId(accepted.conversation_id,"conv")||!validId(accepted.request_id,"req")||conversation&&accepted.conversation_id!==conversation)throw invalid();conversation=accepted.conversation_id,requestId=accepted.request_id}interactive||io.stderr(`Conversation: ${conversation}${requestId?` \xB7 Request: ${requestId}`:""}
|
|
110
|
+
`);let get=async()=>snapshot(await jsonBody(await request(route()),aborter.signal,4259840),conversation),view=await get();if(requestId??=view.active_request_id??view.transcript.entries.at(-1)?.request_id,!requestId)throw new CliError("ASK_FAILED","Conversation has no saved question.");let find=()=>view.transcript.entries.find(entry2=>entry2.request_id===requestId),failureCode;find()?.outcome||(failureCode=await events(await request(`${route()}/events`,"GET",void 0,void 0,!0),conversation,requestId,io,aborter.signal),view=await get());let entry=find();if(!entry?.outcome)throw new CliError("ASK_FAILED","Answer is not persisted yet; reattach to check current status.");if(entry.outcome==="failed"&&failureCode)throw new CliError("ASK_FAILED",failureCode==="unsupported_answer"?"Ask could not produce an answer with valid evidence. Try narrowing your question.":"Evidence could not be verified. Please retry.");if(entry.outcome!=="completed")throw new CliError("ASK_FAILED",`Ask request ${entry.outcome}; conversation history is preserved.`);let finalAnswer=answer(entry.answer);status?.stop(),interactive&&io.stdout(`
|
|
109
111
|
${paint("&","accent")} ${paint("Answer","strong")}
|
|
110
112
|
|
|
111
|
-
`),io.stdout(machineOutput?structured({conversation_id:conversation,request_id:requestId,answer:finalAnswer})
|
|
112
|
-
`),interactive&&io.stderr(`
|
|
113
|
+
`),io.stdout(machineOutput?structured({conversation_id:conversation,request_id:requestId,answer:finalAnswer}):formatAskAnswer(finalAnswer)),interactive&&io.stderr(`
|
|
113
114
|
${paint(`Conversation: ${conversation}`,"muted")}
|
|
114
115
|
`)}catch(error){if(status?.stop(),interactive&&!conversation&&submissionKey&&io.stderr(`Retry the same question with --idempotency-key ${submissionKey}
|
|
115
116
|
`),conversation&&io.stderr(`Reattach: amp ask --watch --conversation ${conversation}
|
|
116
117
|
Disconnecting does not cancel work.
|
|
117
|
-
`),experience().enabled&&conversation){let failure=error instanceof CliError?error:new CliError("ASK_INTERRUPTED","The answer is not available yet. Resume the conversation; disconnecting does not cancel work.");throw failure.nextCommand??=`amp ask --watch --conversation ${conversation}`,failure.details={...failure.details,conversation_id:conversation,resume_command:`amp ask --watch --conversation ${conversation}`},failure}throw error}finally{status?.stop(),io.signal?.removeEventListener("abort",onAbort),aborter.abort()}}function registerAsk(program2){program2.command("ask [question]").description("Ask a question about your workspace data").option("--conversation <id>","continue or attach to a conversation in your tenant").option("--watch","reattach to current status or the latest saved answer").option("--cancel","explicitly cancel current work, preserving history").option("--json","write one final structured answer to stdout").option("--idempotency-key <key>","retry the exact same submission without launching twice").action(async(question,opts)=>{let controller=new AbortController,interrupt=()=>controller.abort();process.once("SIGINT",interrupt),process.once("SIGTERM",interrupt);try{await ask(question,opts,{signal:controller.signal})}finally{process.removeListener("SIGINT",interrupt),process.removeListener("SIGTERM",interrupt)}})}init_experience();init_brand();init_brand();init_http();async function catalog(includeHidden=!1){let result=JSON.parse(await doorRequest("GET","/v1/ontology/object-types"));if(!Array.isArray(result.objectTypes))throw new Error("Invalid schema response.");return result.objectTypes}function publicSchema(row){if(typeof row.apiName!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(row.apiName))throw new Error("Invalid schema response.");return{name:row.apiName,table:`main_${row.apiName}`,description:row.description??"",columns:Object.entries(row.properties??{}).map(([name,property])=>({name,type:property.baseType??"unknown"}))}}async function schema(table,opts){readContext();let rows=(await catalog()).map(publicSchema);if(table!==void 0){let row=rows.find(row2=>row2.name===table||row2.table===table);if(!row)throw new CliError("NOT_FOUND","That table is unavailable in this workspace.",!1,"amp schema");emit(row,opts,()=>`${row.table} \u2014 ${row.description}
|
|
118
|
+
`),experience().enabled&&conversation){let failure=error instanceof CliError?error:new CliError("ASK_INTERRUPTED","The answer is not available yet. Resume the conversation; disconnecting does not cancel work.");throw failure.nextCommand??=`amp ask --watch --conversation ${conversation}`,failure.details={...failure.details,conversation_id:conversation,resume_command:`amp ask --watch --conversation ${conversation}`},failure}throw error}finally{status?.stop(),io.signal?.removeEventListener("abort",onAbort),aborter.abort()}}function registerAsk(program2){program2.command("ask [question]").description("Ask a question about your workspace data").option("--timezone <zone>","Timezone for dates (defaults to your computer timezone)").option("--conversation <id>","continue or attach to a conversation in your tenant").option("--watch","reattach to current status or the latest saved answer").option("--cancel","explicitly cancel current work, preserving history").option("--json","write one final structured answer to stdout").option("--idempotency-key <key>","retry the exact same submission without launching twice").action(async(question,opts)=>{let controller=new AbortController,interrupt=()=>controller.abort();process.once("SIGINT",interrupt),process.once("SIGTERM",interrupt);try{await ask(question,opts,{signal:controller.signal})}finally{process.removeListener("SIGINT",interrupt),process.removeListener("SIGTERM",interrupt)}})}init_experience();init_brand();init_brand();init_http();async function catalog(includeHidden=!1){let result=JSON.parse(await doorRequest("GET","/v1/ontology/object-types"));if(!Array.isArray(result.objectTypes))throw new Error("Invalid schema response.");return result.objectTypes}function publicSchema(row){if(typeof row.apiName!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(row.apiName))throw new Error("Invalid schema response.");return{name:row.apiName,table:`main_${row.apiName}`,description:row.description??"",columns:Object.entries(row.properties??{}).map(([name,property])=>({name,type:property.baseType??"unknown"}))}}async function schema(table,opts){readContext();let rows=(await catalog()).map(publicSchema);if(table!==void 0){let row=rows.find(row2=>row2.name===table||row2.table===table);if(!row)throw new CliError("NOT_FOUND","That table is unavailable in this workspace.",!1,"amp schema");emit(row,opts,()=>`${row.table} \u2014 ${row.description}
|
|
118
119
|
${humanTable(row.columns)}`)}else emit({tables:rows},opts,()=>humanTable(rows.map(row=>({table:row.table,description:row.description,columns:row.columns.length}))))}function registerSchema(program2){program2.command("schema").argument("[table]","type name from the authorized catalog").description("List authorized types and columns").option("--json","compact JSON output").option("--out <file>","write results to a file").action(schema)}init_request_credential();init_machine();init_experience();init_http();var program=new Command().name("amp").description("Query your data with Ampersand").version(CLI_VERSION).option("--profile <name>","select a saved tenant profile").option("--agent","structured JSON for agents; never prompt").option("--human","readable output for people").option("--quiet","hide routine progress").option("--no-input","never open a browser or wait for input").exitOverride().configureOutput({writeErr:()=>{}}).hook("preAction",(_,action)=>{if(configureExperience({...program.opts(),json:action.opts().json}),requestCredentialConfigured()||machineConfigFromEnv())throw new CliError("UNSUPPORTED_IDENTITY","Use a saved human session. Remove machine/request credentials first. Agent output does not change identity.");setProfileOverride(program.opts().profile)});installTerminalHelp(program,{edition:"workspace CLI",examples:["amp login --store <workspace-url>","amp schema",'amp ask "What data is available to me?"']});program.command("login").description("Sign in or manage your local session").option("--store <url>","tenant store HTTPS origin").option("--name <profile>","saved profile name").option("--org <id>","select your organization during sign-in").option("--status","show the signed-in identity").option("--logout","remove credentials for the selected profile on this machine").option("--json","raw JSON output (compatible with existing scripts)").option("--install-skill","install the bundled skill; can run without signing in").option("--skill-dir <path>","install SKILL.md in this directory; requires --install-skill").action(async opts=>{if(opts.status&&opts.logout||(opts.status||opts.logout)&&(opts.store||opts.name||opts.org||opts.installSkill||opts.skillDir))throw new CliError("INVALID_ARGUMENT","Use --status or --logout alone, or sign in with --store.");if(opts.skillDir&&!opts.installSkill)throw new CliError("INVALID_ARGUMENT","--skill-dir requires --install-skill.");let install=()=>installSkill(opts.skillDir?join6(resolve2(opts.skillDir),"SKILL.md"):void 0);if(opts.status)return whoami();if(opts.installSkill&&!opts.store&&!opts.name&&!opts.org){let outcome=install();emit({skill:outcome},opts,()=>`Skill ${outcome}. Start a new agent session to load it.`);return}if(opts.logout){let path=credentialsPath();existsSync6(path)&&await withFileLock(`${path}.lock`,async()=>{rmSync2(path,{force:!0})}),emit({logged_out:!0},opts,()=>"Local session removed.");return}let store=opts.store??activeProfile()?.store_url;if(!store)throw new CliError("WORKSPACE_REQUIRED","Choose your workspace to sign in.",!1,"amp login --store <your tenant store URL>");await login({store,name:opts.name,orgId:opts.org}),opts.installSkill&&process.stdout.write(`Skill ${install()}.
|
|
119
120
|
`)});registerSchema(program);registerSql(program);registerAsk(program);program.parseAsync(process.argv).catch(error=>{if(!(error instanceof CommanderError&&error.exitCode===0)){if(!experience().enabled)try{configureExperience(program.opts())}catch{configureExperience({agent:!0})}reportError(error instanceof CommanderError?new CliError("INVALID_ARGUMENT","Unknown command or invalid arguments. Run amp --help.",!1,"amp --help"):error)}});
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0x26/amp",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"description": "Query your data with Ampersand",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
|
-
"amp": "dist/index.js"
|
|
7
|
+
"amp": "./dist/index.js"
|
|
8
8
|
},
|
|
9
9
|
"engines": {
|
|
10
10
|
"node": ">=20"
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"README.md"
|
|
16
16
|
],
|
|
17
17
|
"publishConfig": {
|
|
18
|
-
"access": "
|
|
18
|
+
"access": "public"
|
|
19
19
|
},
|
|
20
20
|
"license": "UNLICENSED",
|
|
21
21
|
"dependencies": {
|